Directed Acyclic Graphs: Depth-First Search
Explore techniques for finding shortest paths in directed acyclic graphs (DAGs). Learn to leverage depth-first search and dynamic programming to efficiently compute shortest distances in weighted DAGs, including graphs with negative edges but no cycles.
Shortest paths in acyclic graphs
Shortest paths are also easy to compute in directed acyclic graphs, even when the edges are weighted, and in particular, even when some edges have negative weight. (We don’t have to worry about negative cycles because, by definition, dags don’t have any cycles!) Indeed, this is a completely standard dynamic programming algorithm.
Let be a directed graph with weighted edges, and let be the fixed start vertex. For any vertex , let denote the length of the shortest path in from to . This function satisfies the following simple recurrence:
In fact, this identity holds for all directed graphs, but it’s only a recurrence for directed acyclic graphs. If the input graph contained a cycle, a recursive evaluation of this function would fall into an infinite loop; however, because is a dag, each recursive call visits an earlier vertex in topological order.
The dependency graph for this recurrence is the reversal of the input graph ...