![]() |
VOOZH | about |
Given a Weighted Directed Graph and a destination vertex in the graph, find the shortest distance from all vertex to the destination vertex.
Input :
Output : 0 6 10 7 5
Distance of 0 from 0: 0
Distance of 0 from 1: 1+5 = 6 (1->4->0)
Distance of 0 from 2: 10 (2->0)
Distance of 0 from 3: 1+1+5 = 7 (3->1->4->0)
Distance of 0 from 4: 5 (4->0)
Approach: The problem is similar to the Dijkstra's problem..The idea is to use Dijkstra's algorithm. In order to find the shortest distance from all vertex to a given destination vertex we reverse all the edges of the directed graph and use the destination vertex as the source vertex in dijkstra's algorithm. Since all the edges are now reversed computing the shortest distance from the destination vertex to all the other vertex is similar to computing shortest distance from all vertex to a given destination vertex.
After reversing the edges the graph looks like:
Now calculate the shortest distance from the destination vertex as source vertex in Dijkstra's algorithm.
Below is the implementation of the above approach:
Destination Vertex Distance from all vertex 0 0 1 6 2 10 3 7 4 5