Given an undirected graph and a set of vertices, find all reachable nodes from every vertex present in the given set.

Consider below undirected graph with 2 disconnected components.

arr[] = {1 , 2 , 5} Reachable nodes from 1 are 1, 2, 3, 4 Reachable nodes from 2 are 1, 2, 3, 4 Reachable nodes from 5 are 5, 6, 7

**Method 1 (Simple)**

One straight forward solution is to do a BFS traversal for every node present in the set and then find all the reachable nodes.

Assume that we need to find reachable nodes for n nodes, the time complexity for this solution would be O(n*(V+E)) where V is number of nodes in the graph and E is number of edges in the graph. Please note that we need to call BFS as a separate call for every node without using the visited array of previous traversals because a same vertex may need to be printed multiple times. This seems to be an effective solution but consider the case when E = Θ(V

^{2}) and n = V, time complexity becomes O(V

^{3}).

**Method 2 (Efficient)**

Since the given graph is undirected, all vertices that belong to same component have same set of reachable nodes. So we keep track of vertex and component mappings. Every component in the graph is assigned a number and every vertex in this component is assigned this number. We use the visit array for this purpose, the array which is used to keep track of visited vertices in BFS.

For a node u, if visit[u] is 0 then u has not been visited before else // if not zero then visit[u] represents the component number. For any two nodes u and v belonging to same component, visit[u] is equal to visit[v]

To store the reachable nodes, use a map **m** with key as component number and value as a vector which stores all the reachable nodes.

To find reachable nodes for a node **u** return **m[visit[u]]**

Look at the pseudo code below in order to understand how to assign component numbers.

componentNum = 0 for i=1 to n If visit[i] is NOT 0 then componentNum++ // bfs() returns a list (or vector) // for given vertex 'i' list = bfs(i, componentNum) m[visit[i]]] = list

For the graph shown in the example the visit array would be.

For the nodes 1, 2, 3 and 4 the component number is 1. For nodes 5, 6 and 7 the component number is 2.

C++ Implementation of above idea

`// C++ program to find all the reachable nodes ` `// for every node present in arr[0..n-1]. ` `#include <bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// This class represents a directed graph using ` `// adjacency list representation ` `class` `Graph ` `{ ` `public` `: ` ` ` `int` `V; ` `// No. of vertices ` ` ` ` ` `// Pointer to an array containing adjacency lists ` ` ` `list<` `int` `> *adj; ` ` ` ` ` `Graph(` `int` `); ` `// Constructor ` ` ` ` ` `void` `addEdge(` `int` `, ` `int` `); ` ` ` ` ` `vector<` `int` `> BFS(` `int` `, ` `int` `, ` `int` `[]); ` `}; ` ` ` `Graph::Graph(` `int` `V) ` `{ ` ` ` `this` `->V = V; ` ` ` `adj = ` `new` `list<` `int` `>[V+1]; ` `} ` ` ` `void` `Graph::addEdge(` `int` `u, ` `int` `v) ` `{ ` ` ` `adj[u].push_back(v); ` `// Add w to v’s list. ` ` ` `adj[v].push_back(u); ` `// Add v to w’s list. ` `} ` ` ` `vector<` `int` `> Graph::BFS(` `int` `componentNum, ` `int` `src, ` ` ` `int` `visited[]) ` `{ ` ` ` `// Mark all the vertices as not visited ` ` ` `// Create a queue for BFS ` ` ` `queue<` `int` `> queue; ` ` ` ` ` `queue.push(src); ` ` ` ` ` `// Assign Component Number ` ` ` `visited[src] = componentNum; ` ` ` ` ` `// Vector to store all the reachable nodes from 'src' ` ` ` `vector<` `int` `> reachableNodes; ` ` ` ` ` `while` `(!queue.empty()) ` ` ` `{ ` ` ` `// Dequeue a vertex from queue ` ` ` `int` `u = queue.front(); ` ` ` `queue.pop(); ` ` ` ` ` `reachableNodes.push_back(u); ` ` ` ` ` `// Get all adjacent vertices of the dequeued ` ` ` `// vertex u. If a adjacent has not been visited, ` ` ` `// then mark it visited nd enqueue it ` ` ` `for` `(` `auto` `itr = adj[u].begin(); ` ` ` `itr != adj[u].end(); itr++) ` ` ` `{ ` ` ` `if` `(!visited[*itr]) ` ` ` `{ ` ` ` `// Assign Component Number to all the ` ` ` `// reachable nodes ` ` ` `visited[*itr] = componentNum; ` ` ` `queue.push(*itr); ` ` ` `} ` ` ` `} ` ` ` `} ` ` ` `return` `reachableNodes; ` `} ` ` ` `// Display all the Reachable Nodes from a node 'n' ` `void` `displayReachableNodes(` `int` `n, ` ` ` `unordered_map <` `int` `, vector<` `int` `> > m) ` `{ ` ` ` `vector<` `int` `> temp = m[n]; ` ` ` `for` `(` `int` `i=0; i<temp.size(); i++) ` ` ` `cout << temp[i] << ` `" "` `; ` ` ` ` ` `cout << endl; ` `} ` ` ` `// Find all the reachable nodes for every element ` `// in the arr ` `void` `findReachableNodes(Graph g, ` `int` `arr[], ` `int` `n) ` `{ ` ` ` `// Get the number of nodes in the graph ` ` ` `int` `V = g.V; ` ` ` ` ` `// Take a integer visited array and initialize ` ` ` `// all the elements with 0 ` ` ` `int` `visited[V+1]; ` ` ` `memset` `(visited, 0, ` `sizeof` `(visited)); ` ` ` ` ` `// Map to store list of reachable Nodes for a ` ` ` `// given node. ` ` ` `unordered_map <` `int` `, vector<` `int` `> > m; ` ` ` ` ` `// Initialize component Number with 0 ` ` ` `int` `componentNum = 0; ` ` ` ` ` `// For each node in arr[] find reachable ` ` ` `// Nodes ` ` ` `for` `(` `int` `i = 0 ; i < n ; i++) ` ` ` `{ ` ` ` `int` `u = arr[i]; ` ` ` ` ` `// Visit all the nodes of the component ` ` ` `if` `(!visited[u]) ` ` ` `{ ` ` ` `componentNum++; ` ` ` ` ` `// Store the reachable Nodes corresponding to ` ` ` `// the node 'i' ` ` ` `m[visited[u]] = g.BFS(componentNum, u, visited); ` ` ` `} ` ` ` ` ` `// At this point, we have all reachable nodes ` ` ` `// from u, print them by doing a look up in map m. ` ` ` `cout << ` `"Reachable Nodes from "` `<< u <<` `" are\n"` `; ` ` ` `displayReachableNodes(visited[u], m); ` ` ` `} ` `} ` ` ` `// Driver program to test above functions ` `int` `main() ` `{ ` ` ` `// Create a graph given in the above diagram ` ` ` `int` `V = 7; ` ` ` `Graph g(V); ` ` ` `g.addEdge(1, 2); ` ` ` `g.addEdge(2, 3); ` ` ` `g.addEdge(3, 4); ` ` ` `g.addEdge(3, 1); ` ` ` `g.addEdge(5, 6); ` ` ` `g.addEdge(5, 7); ` ` ` ` ` `// For every ith element in the arr ` ` ` `// find all reachable nodes from query[i] ` ` ` `int` `arr[] = {2, 4, 5}; ` ` ` ` ` `// Find number of elements in Set ` ` ` `int` `n = ` `sizeof` `(arr)/` `sizeof` `(` `int` `); ` ` ` ` ` `findReachableNodes(g, arr, n); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

Output:

Reachable Nodes from 2 are 2 1 3 4 Reachable Nodes from 4 are 2 1 3 4 Reachable Nodes from 5 are 5 6 7

**Time Complexity Analysis:**

n = Size of the given set

E = Number of Edges

V = Number of Nodes

O(V+E) for BFS

In worst case all the V nodes are displayed for each node present in the given, i.e only one component in the graph so it takes O(n*V) time.

Worst Case Time Complexity : O(V+E) + O(n*V)

This article is contributed by **Chirag Agarwal**. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Minimum edges to be added in a directed graph so that any node can be reachable from a given node
- Program to print all the non-reachable nodes | Using BFS
- Count the number of non-reachable nodes
- Kth largest node among all directly connected nodes to the given node in an undirected graph
- Minimum nodes to be colored in a Graph such that every node has a colored neighbour
- Count nodes within K-distance from all nodes in a set
- Minimum number of reversals to reach node 0 from every other node
- XOR of all the nodes in the sub-tree of the given node
- Maximize count of nodes disconnected from all other nodes in a Graph
- Queries to check whether a given digit is present in the given Range
- Print the degree of every node from the given Prufer sequence
- Minimum cost path from source node to destination node via an intermediate node
- Minimum cost to reverse edges such that there is path between every pair of nodes
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Check whether the cost of going from any node to any other node via all possible paths is same
- Print all the levels with odd and even number of nodes in it | Set-2
- Program to find average of all nodes in a Linked List
- Find maximum among all right nodes in Binary Tree
- Check if a value is present in an Array in Java