# Minimum edges to be added in a directed graph so that any node can be reachable from a given node

Given a directed graph and a node **X**. The task is to find the minimum number of edges that must be added to the graph such that any node can be reachable from the given node.

**Examples:**

Input:X = 0

Output:3

Input:X = 4

Output:1

**Approach:** First, let’s mark all the vertices reachable from **X** as good, using a simple DFS. Then, for each bad vertex (vertices which are not reachable from X) v, count the number of bad vertices reachable from v (it also can be done by simple DFS). Let this number be cnt_{v}. Now, iterate over all bad vertices in non-increasing order of cnt_{v}. For the current bad vertex v, if it is still not marked as good, run a DFS from it, marking all the reachable vertices as good, and increase the answer by 1 (in fact, we are implicitly adding the edge (s, v)). It can be proved that this solution gives an optimal answer.

Below is the implementation of the above approach:

## C++

`// C++ implementation of the approach ` ` ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `const` `int` `N = 5010; ` ` ` `int` `n, x; ` ` ` `vector<` `int` `> g[N]; ` ` ` `// To check if the vertex has been ` `// visited or not ` `bool` `vis[N]; ` ` ` `// To store if vertex is reachable ` `// from source or not ` `bool` `good[N]; ` ` ` `int` `cnt; ` ` ` `void` `ADD_EDGE(` `int` `u, ` `int` `v) ` `{ ` ` ` `g[u].push_back(v); ` `} ` ` ` `// Function to find all good vertices ` `void` `dfs1(` `int` `v) ` `{ ` ` ` `good[v] = ` `true` `; ` ` ` `for` `(` `auto` `to : g[v]) ` ` ` `if` `(!good[to]) ` ` ` `dfs1(to); ` `} ` ` ` `// Function to find cnt of all unreachable vertices ` `void` `dfs2(` `int` `v) ` `{ ` ` ` `vis[v] = ` `true` `; ` ` ` `++cnt; ` ` ` `for` `(` `auto` `to : g[v]) ` ` ` `if` `(!vis[to] && !good[to]) ` ` ` `dfs2(to); ` `} ` ` ` `// Function to return the minimum edges required ` `int` `Minimum_Edges() ` `{ ` ` ` ` ` `// Find all vertices reachable from the source ` ` ` `dfs1(x); ` ` ` ` ` `// To store all vertices with their cnt value ` ` ` `vector<pair<` `int` `, ` `int` `> > val; ` ` ` ` ` `for` `(` `int` `i = 0; i < n; ++i) { ` ` ` ` ` `// If vertex is bad i.e. not reachable ` ` ` `if` `(!good[i]) { ` ` ` `cnt = 0; ` ` ` `memset` `(vis, ` `false` `, ` `sizeof` `(vis)); ` ` ` ` ` `// Find cnt of this vertex ` ` ` `dfs2(i); ` ` ` `val.push_back(make_pair(cnt, i)); ` ` ` `} ` ` ` `} ` ` ` ` ` `// Sort all unreachable vertices in ` ` ` `// non-decreasing order of their cnt values ` ` ` `sort(val.begin(), val.end()); ` ` ` `reverse(val.begin(), val.end()); ` ` ` ` ` `// Find the minimum number of edges ` ` ` `// needed to be added ` ` ` `int` `ans = 0; ` ` ` `for` `(` `auto` `it : val) { ` ` ` `if` `(!good[it.second]) { ` ` ` `++ans; ` ` ` `dfs1(it.second); ` ` ` `} ` ` ` `} ` ` ` ` ` `return` `ans; ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `// Number of nodes and source node ` ` ` `n = 5, x = 4; ` ` ` ` ` `// Add edges to the graph ` ` ` `ADD_EDGE(0, 1); ` ` ` `ADD_EDGE(1, 2); ` ` ` `ADD_EDGE(2, 3); ` ` ` `ADD_EDGE(3, 0); ` ` ` ` ` `cout << Minimum_Edges(); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Python3

# Python3 implementation of the approach

N = 5010

g = [[] for i in range(N)]

# To check if the vertex

# has been visited or not

vis = [False for i in range(N)]

# To store if vertex is reachable

# from source or not

good = [False for i in range(N)]

def ADD_EDGE(u, v):

g[u].append(v)

# Function to find all good vertices

def dfs1(v):

good[v] = True

for to in g[v]:

if not good[to]:

dfs1(to)

# Function to find cnt of

# all unreachable vertices

def dfs2(v):

global cnt

vis[v] = True

cnt += 1

for to in g[v]:

if not vis[to] and not good[to]:

dfs2(to)

# Function to return

# the minimum edges required

def Minimum_Edges():

global vis, cnt

# Find all vertices reachable

# from the source

dfs1(x)

# To store all vertices

# with their cnt value

val = []

for i in range(0, n):

# If vertex is bad i.e. not reachable

if not good[i]:

cnt = 0

vis = [False for i in range(N)]

# Find cnt of this vertex

dfs2(i)

val.append((cnt, i))

# Sort all unreachable vertices

# in non-decreasing order of

# their cnt values

val.sort(reverse = True)

# Find the minimum number of edges

# needed to be added

ans = 0

for it in val:

if not good[it[1]]:

ans += 1

dfs1(it[1])

return ans

# Driver code

if __name__ == “__main__”:

# Number of nodes and source node

n, x = 5, 4

# Add edges to the graph

ADD_EDGE(0, 1)

ADD_EDGE(1, 2)

ADD_EDGE(2, 3)

ADD_EDGE(3, 0)

print(Minimum_Edges())

# This code is contributed by Rituraj Jain

**Output:**

1

## Recommended Posts:

- Minimum cost path from source node to destination node via an intermediate node
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Find all reachable nodes from every node present in a given set
- Shortest path with exactly k edges in a directed and weighted graph
- Assign directions to edges so that the directed graph remains acyclic
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph
- Right sibling of each node in a tree given as array of edges
- Minimum number of edges between two vertices of a Graph
- Minimum number of edges between two vertices of a graph using DFS
- k'th heaviest adjacent node in a graph where each vertex has weight
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Count single node isolated sub-graphs in a disconnected graph
- Level of Each node in a Tree from source node (using BFS)
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Find the node whose xor with x gives minimum value

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.