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 a depth-first search.
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. 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 the below implementation, DFS is used. We do DFS 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 DFS. In DFS, if we start from the 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 marked as visited from the head node.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count the nodes whose sum with X is a Fibonacci number
- Count the number of nodes at given level in a tree using BFS.
- Count the number of nodes at a given level in a tree using DFS
- Count the nodes in the given tree whose weight is a powerful number
- Count nodes in the given tree whose weight is a fibonacci number
- Count the nodes in the given Tree whose weight is a Perfect Number
- Count nodes within K-distance from all nodes in a set
- Print levels with odd number of nodes and even number of nodes
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count the nodes in the given tree whose weight is even
- Count the nodes in the given tree whose sum of digits of weight is odd
- Count the nodes in the given tree whose weight is even parity
- Find count of pair of nodes at even distance
- Count the nodes in the given tree whose weight is a power of two
- Count of nodes having odd divisors in the given subtree for Q queries
- Count the nodes of the given tree whose weight has X as a factor
- Count the nodes whose weight is a perfect square
- Count the nodes in the given tree whose weight is prime
- Count the nodes of the given tree whose weighted string is a palindrome
- Count the nodes of the tree whose weighted string contains a vowel
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.