Find all reachable nodes from every node present in a given set
Last Updated : 27 Aug, 2024
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 = Θ(V2) and n = V, time complexity becomes O(V3).
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.
Implementation of above idea
C++ // 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 and 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; }
Java // Java Code // import java.util.*; public class ReachableNodes { private static int V; private static List<List<Integer> > adj; private static boolean[] visited; public static void addEdge(int v, int w) { adj.get(v).add(w); adj.get(w).add(v); } public static List<Integer> BFS(int componentNum, int src) { List<Integer> queue = new ArrayList<>(); queue.add(src); visited[src] = true; List<Integer> reachableNodes = new ArrayList<>(); while (!queue.isEmpty()) { int u = queue.remove(0); reachableNodes.add(u); for (int itr : adj.get(u)) { if (visited[itr] == false) { visited[itr] = true; queue.add(itr); } } } return reachableNodes; } public static void displayReachableNodes(List<Integer> m) { for (int i : m) { System.out.print(i + " "); } System.out.println(); } public static void findReachableNodes(int[] arr, int n) { List<Integer> a = new ArrayList<>(); int componentNum = 0; for (int i = 0; i < n; i++) { int u = arr[i]; if (visited[u] == false) { componentNum++; a = BFS(componentNum, u); } System.out.println("Reachable Nodes from " + u + " are"); displayReachableNodes(a); } } public static void main(String[] args) { V = 7; adj = new ArrayList<>(); for (int i = 0; i < V + 1; i++) { adj.add(new ArrayList<>()); } visited = new boolean[V + 1]; addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(3, 1); addEdge(5, 6); addEdge(5, 7); int[] arr = { 2, 4, 5 }; int n = arr.length; findReachableNodes(arr, n); } }
Python # Python3 program to find all the reachable nodes # for every node present in arr[0..n-1] from collections import deque def addEdge(v, w): global visited, adj adj[v].append(w) adj[w].append(v) def BFS(componentNum, src): global visited, adj # Mark all the vertices as not visited # Create a queue for BFS #a = visited queue = deque() queue.append(src) # Assign Component Number visited[src] = 1 # Vector to store all the reachable # nodes from 'src' reachableNodes = [] #print("0:",visited) while (len(queue) > 0): # Dequeue a vertex from queue u = queue.popleft() reachableNodes.append(u) # Get all adjacent vertices of the dequeued # vertex u. If a adjacent has not been visited, # then mark it visited and enqueue it for itr in adj[u]: if (visited[itr] == 0): # Assign Component Number to all the # reachable nodes visited[itr] = 1 queue.append(itr) return reachableNodes # Display all the Reachable Nodes # from a node 'n' def displayReachableNodes(m): for i in m: print(i, end = " ") print() def findReachableNodes(arr, n): global V, adj, visited # Get the number of nodes in the graph # Map to store list of reachable Nodes for a # given node. a = [] # Initialize component Number with 0 componentNum = 0 # For each node in arr[] find reachable # Nodes for i in range(n): u = arr[i] # Visit all the nodes of the component if (visited[u] == 0): componentNum += 1 # Store the reachable Nodes corresponding # to the node 'i' a = BFS(componentNum, u) # At this point, we have all reachable nodes # from u, print them by doing a look up in map m. print("Reachable Nodes from ", u, " are") displayReachableNodes(a) # Driver code if __name__ == '__main__': V = 7 adj = [[] for i in range(V + 1)] visited = [0 for i in range(V + 1)] addEdge(1, 2) addEdge(2, 3) addEdge(3, 4) addEdge(3, 1) addEdge(5, 6) addEdge(5, 7) # For every ith element in the arr # find all reachable nodes from query[i] arr = [ 2, 4, 5 ] # Find number of elements in Set n = len(arr) findReachableNodes(arr, n) # This code is contributed by mohit kumar 29
C# // C# program to find all the reachable nodes // for every node present in arr[0..n-1]. using System; using System.Collections.Generic; // This class represents a directed graph using // adjacency list representation public class ReachableNodes { private static int V; // No. of vertices // Pointer to an array containing adjacency lists private static List<List<int> > adj; private static bool[] visited; public static void AddEdge(int v, int w) { adj[v].Add(w); // Add w to v’s list. adj[w].Add(v); // Add v to w’s list. } public static List<int> BFS(int componentNum, int src) { // Mark all the vertices as not visited // Create a queue for BFS List<int> queue = new List<int>(); queue.Add(src); // Assign Component Number visited[src] = true; // Vector to store all the reachable nodes from // 'src' List<int> reachableNodes = new List<int>(); while (queue.Count > 0) { // Dequeue a vertex from queue int u = queue[0]; queue.RemoveAt(0); reachableNodes.Add(u); // Get all adjacent vertices of the dequeued // vertex u. If a adjacent has not been visited, // then mark it visited and enqueue it foreach(int itr in adj[u]) { if (visited[itr] == false) { // Assign Component Number to all the // reachable nodes visited[itr] = true; queue.Add(itr); } } } return reachableNodes; } // Display all the Reachable Nodes from a node 'n' public static void DisplayReachableNodes(List<int> m) { foreach(int i in m) { Console.Write(i + " "); } Console.WriteLine(); } // Find all the reachable nodes for every element // in the arr public static void FindReachableNodes(int[] arr, int n) { List<int> a = new List<int>(); // 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]; if (visited[u] == false) { // Store the reachable Nodes // corresponding to // the node 'i' componentNum++; a = BFS(componentNum, u); } // At this point, we have all reachable nodes // from u, print them by doing a look up in map // m. Console.WriteLine("Reachable Nodes from " + u + " are"); DisplayReachableNodes(a); } } // Driver code public static void Main(string[] args) { // Create a graph given in the above diagram V = 7; adj = new List<List<int> >(); for (int i = 0; i < V + 1; i++) { adj.Add(new List<int>()); } visited = new bool[V + 1]; AddEdge(1, 2); AddEdge(2, 3); AddEdge(3, 4); AddEdge(3, 1); AddEdge(5, 6); 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 = arr.Length; FindReachableNodes(arr, n); } }
JavaScript // This function adds an edge between two vertices function addEdge(v, w) { adj[v].push(w); adj[w].push(v); } // This function performs BFS on a connected component starting at a source vertex and returns the reachable nodes function BFS(componentNum, src) { let queue = []; queue.push(src); visited[src] = true; let reachableNodes = []; while (queue.length != 0) { let u = queue.shift(); reachableNodes.push(u); for (let itr of adj[u]) { if (visited[itr] == false) { visited[itr] = true; queue.push(itr); } } } return reachableNodes; } // This function displays the reachable nodes from a source vertex function displayReachableNodes(m) { for (let i of m) { console.log(i + " "); } console.log(); } // This function finds the reachable nodes from each vertex in the array arr function findReachableNodes(arr, n) { let a = []; let componentNum = 0; for (let i = 0; i < n; i++) { let u = arr[i]; if (visited[u] == false) { componentNum++; a = BFS(componentNum, u); } console.log("Reachable Nodes from " + u + " are"); displayReachableNodes(a); } } // Main function let V = 7; let adj = new Array(V + 1); for (let i = 0; i < V + 1; i++) { adj[i] = new Array(); } let visited = new Array(V + 1).fill(false); addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(3, 1); addEdge(5, 6); addEdge(5, 7); let arr = [2, 4, 5]; let n = arr.length; findReachableNodes(arr, n);
OutputReachable 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)
Similar Reads
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
BFS in different language
BFS for Disconnected Graph In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
14 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS) We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
4 min read
Breadth First Traversal ( BFS ) on a 2D array Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0,
9 min read
0-1 BFS (Shortest Path in a Binary Weight Graph) Given an undirected graph where every edge has a weight as either 0 or 1. The task is to find the shortest path from the source vertex to all other vertices in the graph.Example: Input: Source Vertex = 0 and below graph Having vertices like (u, v, w): edges: [[0,1,0], [0, 7, 1], [1,2,1], [1, 7, 1],
10 min read
Variations of BFS implementations
Easy problems on BFS
Find if there is a path between two vertices in a directed graphGiven a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest =
11 min read
Find if there is a path between two vertices in an undirected graphGiven an undirected graph with N vertices and E edges and two vertices (U, V) from the graph, the task is to detect if a path exists between these two vertices. Print "Yes" if a path exists and "No" otherwise. Examples: U = 1, V = 2 Output: No Explanation: There is no edge between the two points and
15+ min read
Print all the levels with odd and even number of nodes in it | Set-2Given an N-ary tree, print all the levels with odd and even number of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2 No
12 min read
Finding the path from one vertex to rest using BFSGiven an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS. Examples: Input: Output: 0 <- 2 1 <- 0 <- 2 2 3 <- 1 <- 0 <- 2 4 <- 5 <- 2 5 <- 2 6 <- 2 Approach: In the images shown below:
14 min read
Find all reachable nodes from every node present in a given setGiven 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, 4Reachable nodes from 2 are 1, 2, 3, 4Reachable nodes from 5 ar
12 min read
Program to print all the non-reachable nodes | Using BFSGiven an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search. For example: Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2
8 min read
Check whether a given graph is Bipartite or notGiven a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i
8 min read
Print all paths from a given source to a destination using BFSGiven a directed graph, a source vertex âsrcâ and a destination vertex âdstâ, print all paths from given âsrcâ to âdstâ. Please note that in the cases, we have cycles in the graph, we need not to consider paths have cycles as in case of cycles, there can by infinitely many by doing multiple iteratio
9 min read
Minimum steps to reach target by a Knight | Set 1Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.Examples: Input: KnightknightPosition: (1, 3) , targetPosition: (5, 0)Output: 3Explanation: In above diagr
9 min read
Intermediate problems on BFS
Traversal of a Graph in lexicographical order using BFSC++ // C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to traverse the graph in // lexicographical order using BFS void LexiBFS(map<char, set<char> >& G, char S, map<char, bool>& vis) { // Stores nodes of the gr
8 min read
Detect cycle in an undirected graph using BFSGiven an undirected graph, the task is to determine if cycle is present in it or not.Examples:Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]Undirected Graph with 5 NodeOutput: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0.Input: V = 4, edges[][] = [[0, 1], [1,
6 min read
Detect Cycle in a Directed Graph using BFSGiven a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0->1->2->3->0 and 2->4->2, so your function must return
11 min read
Minimum number of edges between two vertices of a GraphYou are given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). Examples: Input: For given graph G. Find minimum number of edges between (1, 5). Output: 2Explanation: (1, 2) and (2, 5) are the only edges resu
8 min read
Word Ladder - Shortest Chain To Reach Target WordGiven an array of strings arr[], and two different strings start and target, representing two words. The task is to find the length of the smallest chain from string start to target, such that only one character of the adjacent words differs and each word exists in arr[].Note: Print 0 if it is not p
15 min read
Print the lexicographically smallest BFS of the graph starting from 1Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1. Note: The vertices are numbered from 1 to N.Examples: Input: N = 5, M = 5 Edges: 1 4 3 4 5 4 3 2 1 5 Output: 1 4 3 2 5 Start from 1, go to 4, then to 3
7 min read
Shortest path in an unweighted graphGiven an unweighted, undirected graph of V nodes and E edges, a source node S, and a destination node D, we need to find the shortest path from node S to node D in the graph. Input: V = 8, E = 10, S = 0, D = 7, edges[][] = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {4, 7}, {3, 7}, {6, 7}, {4, 5}, {4, 6}, {5,
11 min read
Number of shortest paths in an unweighted and directed graphGiven an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shorte
11 min read
Distance of nearest cell having 1 in a binary matrixGiven a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell.The distance is calculated as |i1 - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1. Th
15+ min read
Hard Problems on BFS
Islands in a graph using BFSGiven an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
15+ min read
Print all shortest paths between given source and destination in an undirected graphGiven an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 ->
13 min read
Count Number of Ways to Reach Destination in a Maze using BFSGiven a maze of dimensions n x m represented by the matrix mat, where mat[i][j] = -1 represents a blocked cell and mat[i][j] = 0 represents an unblocked cell, the task is to count the number of ways to reach the bottom-right cell starting from the top-left cell by moving right (i, j+1) or down (i+1,
8 min read
Coin Change | BFS ApproachGiven an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4}
6 min read
Water Jug problem using BFSGiven two empty jugs of m and n litres respectively. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water. The task is to find the minimum number of operations to be performed to obtain d litres of water in one of the jugs. In case
12 min read
Word Ladder - Set 2 ( Bi-directional BFS )Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may b
15+ min read
Implementing Water Supply Problem using Breadth First SearchGiven N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are b
10 min read
Minimum Cost Path in a directed graph via given set of intermediate nodesGiven a weighted, directed graph G, an array V[] consisting of vertices, the task is to find the Minimum Cost Path passing through all the vertices of the set V, from a given source S to a destination D. Examples: Input: V = {7}, S = 0, D = 6 Output: 11 Explanation: Minimum path 0->7->5->6.
10 min read
Shortest path in a Binary MazeGiven an M x N matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.Note: You can move into an adjacent cell in one of the four directions, Up, Down, Left, and
15+ min read
Minimum cost to traverse from one index to another in the StringGiven a string S of length N consisting of lower case character, the task is to find the minimum cost to reach from index i to index j. At any index k, the cost to jump to the index k+1 and k-1(without going out of bounds) is 1. Additionally, the cost to jump to any index m such that S[m] = S[k] is
10 min read