Given a directed graph and a source vertex in the graph, the task is to find the shortest distance and path from source to target vertex in the given graph where edges are weighted (non-negative) and directed from parent vertex to source vertices.
- Mark all vertices unvisited. Create a set of all unvisited vertices.
- Assign zero distance value to source vertex and infinity distance value to all other vertices.
- Set the source vertex as current vertex
- For current vertex, consider all of its unvisited children and calculate their tentative distances through the current. (distance of current + weight of the corresponding edge) Compare the newly calculated distance to the current assigned value (can be infinity for some vertices) and assign the smaller one.
- After considering all the unvisited children of the current vertex, mark the current as visited and remove it from the unvisited set.
- Similarly, continue for all the vertex until all the nodes are visited.
Below is the implementation of the above approach:
Distance of 0th vertex from source vertex 0 is: 0
Distance of 1th vertex from source vertex 0 is: 1
Distance of 2th vertex from source vertex 0 is: 3
Distance of 3th vertex from source vertex 0 is: 6
Related articles: We have already discussed the shortest path in directed graph using Topological Sorting, in this article: Shortest path in Directed Acyclic graph
- Shortest Path in Directed Acyclic Graph
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- Shortest path with exactly k edges in a directed and weighted graph
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Number of shortest paths in an unweighted and directed graph
- Path with minimum XOR sum of edges in a directed graph
- Longest Path in a Directed Acyclic Graph
- Find if there is a path between two vertices in a directed graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Hierholzer's Algorithm for directed graph
- Longest path in a directed Acyclic graph | Dynamic Programming
- Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
- Why Prim’s and Kruskal's MST algorithm fails for Directed Graph?
- Multistage Graph (Shortest Path)
- Shortest path in a complement graph
- Shortest path in an unweighted graph
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Dijkstra’s shortest path algorithm using set in STL
- Shortest Path Faster Algorithm
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.