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 are reachable. We mark all the reachable nodes as visited. All those nodes which are not marked as visited i.e, node 3 and 4 are non-reachable nodes.
Input: 5 0 1 0 2 1 2 3 4 Output: 3 4 Input: 8 0 1 0 2 1 2 3 4 4 5 6 7 Output: 3 4 5 6 7
- We can either use BFS or DFS for this purpose. Set 1 of this article implements the DFS approach. In this article, BFS approach is used.
- We do BFS from a given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visited array for this purpose, the array which is used to keep track of non-visited vertices in BFS.
- BFS is a traversing algorithm which starts traversing from a selected node (source or starting node) and traverses the graph layer-wise thus exploring the neighbour nodes (nodes which are directly connected to source node). Then, move towards the next-level neighbour nodes.
Below is the implementation of the above approach:
3 4 5 6 7
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.
- Print all paths from a given source to a destination using BFS
- Count the number of nodes at given level in a tree using BFS.
- Print the lexicographically smallest BFS of the graph starting from 1
- Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
- Traversing directory in Java using BFS
- BFS using STL for competitive coding
- Water Jug problem using BFS
- Diameter of n-ary tree using BFS
- Level of Each node in a Tree from source node (using BFS)
- BFS using vectors & queue as per the algorithm of CLRS
- Detect cycle in an undirected graph using BFS
- Detect Cycle in a Directed Graph using BFS
- Finding the path from one vertex to rest using BFS
- Islands in a graph using BFS
- Count number of ways to reach destination in a Maze using BFS
- Implementation of BFS using adjacency matrix
- Find integral points with minimum distance from given set of integers using BFS
- Breadth First Search or BFS for a Graph
- BFS vs DFS for Binary Tree
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.