Proofs: Shortest paths in a DAG
These are the human proofs of Shortest paths in a DAG, at full length.
Relaxing in topological order gives shortest paths in a DAG full
This proof shows: correctness, termination.
Claim. Let be a directed acyclic graph with real weights and a source . DAG-SHORTEST-PATHS ends, and at the end for each . For each with , nil and .
Termination. Line L1 ends (Kahn's algorithm makes at most passes of its loop). The loop of line L4 visits each of the vertices once, and the inner loop visits each edge out of the current vertex once. So the algorithm ends.
Setup. Let be the order from line L1: for each edge , . Since has no cycle, every walk is a path, so is the least weight of a path from to (there are finitely many), or if there is none. A path visits vertices in increasing position, because each edge goes forward. We use the upper-bound property: at all times, and never increases.
Invariant. For : when the loop of line L4 is about to visit (or has ended, for ), for each (for ).
We prove the stronger statement : at the moment the loop starts the visit of , . Values do not change after they equal (they cannot go lower), and a vertex is visited before all later ones, so give the invariant and the claim.
Proof of , by strong induction on . Assume for all .
Case . By the upper-bound property .
Case . No path from to has an edge, because a nonempty one would be a cycle; so . by line L3, and it never drops below .
Case and . Take a shortest path . Its last edge goes forward, so , and its prefix is a shortest path to : a shorter path to plus the edge would give a shorter path to , and it would still be a path, since has no cycle. So and . By , when is visited, so line L5 lets the inner loop run, and line L7 relaxes . After it, . Later steps before the visit of only lower , and the upper-bound property gives . So when the visit of starts. This proves .
Predecessors. Let with . Then was set by line L8, which also set with at that time, and was being visited, so was already final. Later, changes only together with . So at the end . Each predecessor comes earlier in the order, so following from ends, and it ends at , the only reachable vertex without a predecessor. Thus the predecessor edges form a shortest-path tree.
Where acyclicity is used. Twice: a shortest path to enters it from an earlier vertex, and the prefix of a shortest path, extended by an edge, is still a path. With a cycle, both steps fail; this is why line L1 must check for one.