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
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- 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
- Find if there is a path between two vertices in a directed graph
- Longest Path in a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Find if there is a path between two vertices in a directed graph | Set 2
- Longest path in a directed Acyclic graph | Dynamic Programming
- Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
- Path with minimum XOR sum of edges in a directed graph
- Minimum Cost Path in a directed graph via given set of intermediate nodes
- Convert undirected connected graph to strongly connected directed graph
- Hierholzer's Algorithm for directed graph
- Why Prim’s and Kruskal's MST algorithm fails for Directed Graph?
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Multistage Graph (Shortest Path)