Count nodes within K-distance from all nodes in a set
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 or equal to K that means every node whose distance from all marked nodes is less than or equal to 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 or eual to 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.
Time Complexity: O(E+V) (as we do 2 times bfs so overall time complexity is as same as time complexity for BFS)
Space Complexity: O(V) (auxilary space required for queue todo BFS)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.