Given an undirected tree with some marked nodes and a positive number K. We need to print the count of all such nodes which have distance from all marked nodes less than K that means every node whose distance from all marked nodes is less than K, should be counted in the result.
In above tree we can see that node with index 0, 2, 3, 5, 6, 7 have distances less than 3 from all the marked nodes. so answer will be 6
We can solve this problem using breadth first search. Main thing to observe in this problem is that if we find two marked nodes which are at largest distance from each other considering all pairs of marked nodes then if a node is at a distance less than K from both of these two nodes then it will be at a distance less than K from all the marked nodes because these two nodes represents the extreme limit of all marked nodes, if a node lies in this limit then it will be at a distance less than K from all marked nodes otherwise not.
As in above example, node-1 and node-4 are most distant marked node so nodes which are at distance less than 3 from these two nodes will also be at distance less than 3 from node 2 also. Now first distant marked node we can get by doing a bfs from any random node, second distant marked node we can get by doing another bfs from marked node we just found from the first bfs and in this bfs we can also found distance of all nodes from first distant marked node and to find distance of all nodes from second distant marked node we will do one more bfs, so after doing these three bfs we can get distance of all nodes from two extreme marked nodes which can be compared with K to know which nodes fall in K-distance range from all marked nodes.
This article is contributed by Utkarsh Trivedi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count the number of non-reachable nodes
- Count the number of nodes at given level in a tree using BFS.
- Subtree of all nodes in a tree using DFS
- Check if two nodes are on same path in a tree
- Number of Unicolored Paths between two nodes
- Number of sink nodes in a graph
- Print all the levels with odd and even number of nodes in it | Set-2
- Print Nodes in Top View of Binary Tree
- Minimize the number of weakly connected nodes
- Find all reachable nodes from every node present in a given set
- Maximize number of nodes which are not part of any edge in a Graph
- Paths to travel each nodes using each edge (Seven Bridges of Königsberg)
- Minimum cost to connect weighted nodes represented as array
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
- Count all possible paths between two vertices