Search⌘ K

Directed Acyclic Graphs: Depth-First Search

Explore how to find shortest paths in directed acyclic graphs (DAGs) using depth-first search and topological sorting. Understand the dynamic programming approach for DAG shortest paths involving edge relaxation and recursive distance calculation. Gain practical knowledge of implementing these algorithms in Java, including handling weighted edges and ensuring efficient computation without 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 GG be a directed graph with weighted edges, and let ss be the fixed start vertex. For any vertex vv, let dist(v)dist(v) denote the length of the shortest path in GG from ss to vv. This function satisfies the following simple recurrence:

dist(v){0if v=sminuv(dist(u)+w(uv))otherwisedist(v)\begin{cases} & 0 \hspace{4.1cm} if\space v=s \\ & \underset{u\rightarrow v}{min}(dist(u) + w(u\rightarrow v)) \hspace{0.4cm} otherwise \end{cases}

In fact, this identity holds for all directed graphs, but it is only a recurrence for directed acyclic graphs. If the input graph GG contained a cycle, a recursive evaluation of this function would fall into an infinite loop; however, because GG 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 GG: subproblem dist(v)dist(v) depends on dist(u ...