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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print all the levels with odd and even number of nodes in it | Set-2
- Print the path between any two nodes of a tree | DFS
- Print all neighbour nodes within distance K
- Print the nodes having exactly one child in a Binary tree
- Print Nodes in Top View of Binary Tree
- Print nodes having maximum and minimum degrees
- Program to delete all even nodes from a Singly Linked List
- Count nodes within K-distance from all nodes in a set
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Subtree of all nodes in a tree using DFS
- XOR of all the nodes in the sub-tree of the given node
- Count the number of non-reachable nodes
- Sum of degrees of all nodes of a undirected graph
- Number of special nodes in an n-ary tree
- Count the nodes in the given tree whose weight is even
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.