Given an undirected graph and a set of vertices, we have to count the number of non reachable nodes from the given head node using depth first search.
Consider below undirected graph with two disconnected components:
In this graph if we consider 0 as 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 mark as visited i.e, node 3 and 4 are non reachable nodes. Hence their count is 2.
Input : 5 0 1 0 2 1 2 3 4 Output : 2
We can either use BFS or DFS for this purpose. In below implementation DFS is used. We do DFS from given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visit array for this purpose, the array which is used to keep track of non-visited vertices in DFS. In DFS, if we start from head node it will mark all the nodes connected to the head node as visited. Then after traversing the graph we count the number of nodes that are not mark as visited from the head node.
- Find the Degree of a Particular vertex in a Graph
- Level of Each node in a Tree from source node (using BFS)
- Katz Centrality (Centrality Measure)
- Count all possible paths between two vertices
- Count single node isolated sub-graphs in a disconnected graph
- Minimum edges required to add to make Euler Circuit
- Find all reachable nodes from every node present in a given set
- Find the number of Islands | Set 2 (Using Disjoint Set)
- Find if there is a path of more than k length from a source
- Print all paths from a given source to a destination
- Check if a given graph is tree or not
- Eulerian path and circuit for undirected graph
- Bridges in a graph
- Transitive closure of a graph
- Dijkstra's shortest path algorithm | Greedy Algo-7
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.