Given a weighted undirected connected graph with N nodes and M edges. Some of the nodes are marked as good. The task is to find the shortest distance between any pair of two different good nodes.
Note: Nodes marked as yellow in the below examples are considered to be good nodes.
Input : Output : 7 Explanation : Pairs of Good Nodes and distance between them are: (1 to 3) -> distance: 7, (3 to 5) -> distance: 9, (1 to 5) -> distance: 16, out of which 7 is the minimum. Input : Output : 4
Approach : Let us start by thinking of an algorithm to solve a simpler version of the given problem wherein all edges are of weight 1.
- Pick a random good node and perform a BFS from this point and stop at the first level say which contains another good node.
- We know that the minimum distance between any two good nodes can’t be more than s. So we again take a good node at random which is not already taken before and perform a BFS again. If we don’t find any special node in s distance, we terminate the search. If we do, then we update the value of s and repeat the procedure with some other special node taken at random.
We can apply a similar algorithm when weights are multiple.
Below is the implementation of the above approach:
- Find count of pair of nodes at even distance
- Find Shortest distance from a guard in a Bank
- Queries to find distance between two nodes of a Binary tree
- Find distance between two nodes in the given Binary tree for Q queries
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Find the number of pair of Ideal nodes in a given tree
- Shortest distance between a point and a circle
- Shortest distance between a Line and a Point in a 3-D plane
- Shortest distance from the centre of a circle to a chord
- Sum of shortest distance on source to destination and back having at least a common vertex
- Count nodes within K-distance from all nodes in a set
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Check if given path between two nodes of a graph represents a shortest paths
- Print all neighbour nodes within distance K
- Find the number of good permutations
- Find all good indices in the given Array
- Count of nodes which are at a distance X from root and leaves
- Find the good permutation of first N natural numbers
- Find two disjoint good sets of vertices in a given graph
- Find the minimum number of elements that should be removed to make an array good
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.