Given a weighted directed acyclic graph (DAG) and a source vertex, find the shortest path’s cost from the source vertex to all other vertices present in the graph. If the vertex can’t be reached from the given source vertex, return its distance as infinity.

For example, consider the following DAG,

 
Shortest Path in DAG

The shortest distance of source vertex 7 to every other vertex is:

dist(7, 0) =  6 (7 —> 0)
dist(7, 1) = -2 (7 —> 5 —> 1)
dist(7, 2) = -6 (7 —> 5 —> 1 —> 2)
dist(7, 3) =  4 (7 —> 3)
dist(7, 4) = -1 (7 —> 5 —> 1 —> 4)
dist(7, 5) = -4 (7 —> 5)
dist(7, 6) =  6 (7 —> 5 —> 1 —> 6)

Practice this problem

We know that a Topological sort of a directed acyclic graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.

Topological order shortest path

We can use a topological sort to solve this problem. When we consider a vertex u in topological order, it is guaranteed that we have considered every incoming edge to it. Now for each vertex v of the DAG in the topological order, we relax the cost of its outgoing edges (update the shortest path information). In order words, since we have already found the shortest path to vertex v, we can use that info to update the shortest path of all its adjacent vertices, i.e.,

for each vertex u in topological order
    for each edge (u, v) with weight w
        if (distance[u] + w < distance[v])
            distance[v] = distance[u] + w

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
dist(7, 0) = 6
dist(7, 1) = -2
dist(7, 2) = -6
dist(7, 3) = 4
dist(7, 4) = -1
dist(7, 5) = -4
dist(7, 6) = 6
dist(7, 7) = 0

The time complexity of the above solution is O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.

 
The related problem is to find the longest paths from the given source vertex to all other vertices present in the graph. The implementation can be seen below:

 

Find the longest path in a Directed Acyclic Graph (DAG)

 
References: https://en.wikipedia.org/wiki/Topological_sorting#Application_to_shortest_path_finding