Given a Weighted Directed Graph and a destination vertex in the graph, find the shortest distance from all vertex to the destination vertex.
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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print all paths from a given source to a destination
- Print all paths from a given source to a destination using BFS
- Count all possible paths between two vertices
- Find maximum number of edge disjoint paths between two vertices
- Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
- Johnson's algorithm for All-pairs shortest paths
- Printing Paths in Dijkstra's Shortest Path Algorithm
- Johnson’s algorithm for All-pairs shortest paths | Implementation
- Number of shortest paths in an unweighted and directed graph
- Check if given path between two nodes of a graph represents a shortest paths
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Number of shortest paths to reach every cell from bottom-left cell in the grid
- Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
- Find K vertices in the graph which are connected to at least one of remaining vertices
- Minimum steps to reach a destination
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.