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 email@example.com. 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.
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.