Proofs: Johnson's algorithm
These are the human proofs of Johnson's algorithm, at full length.
Johnson's algorithm returns all distances or reports a negative cycle full
This proof shows: correctness, termination.
Let be a directed graph with vertices, arcs and real weights . Line numbers refer to the pseudocode of JOHNSON on the main page.
Fact 1 (cycles of ). The graph of line L1 has a negative cycle if and only if has one.
Proof. The new vertex has no incoming arc, so no cycle of passes through . Hence the cycles of are exactly the cycles of , with the same weights.
Fact 2 (line L3). Line L3 returns "negative cycle" if and only if has a negative cycle.
Proof. Every vertex of is reachable from by its arc . Bellman-Ford from reports a negative cycle exactly when a negative cycle is reachable from (see Bellman-Ford). Since every cycle is reachable from , this happens exactly when has a negative cycle, which by Fact 1 is when has one.
From now on, assume has no negative cycle.
Fact 3 ( is real). For every , is a real number with .
Proof. is reachable from , so . No negative cycle exists in , so . The arc of weight 0 gives .
Fact 4 (). For every arc , .
Proof. A shortest path from to followed by is a walk from to of weight , so . This is the triangle inequality of the optimality conditions. Rearranged, it is .
Lemma (reweighting). For every walk in , . Hence for all , is reachable from under if and only if under , and when it is, .
Proof. Sum the reduced costs along :
because the sum of telescopes. The two weight functions are on the same arc set, so the walks from to are the same set in both cases, and reachability is the same. Each walk from to changes by the same real constant , so the infimum over these walks changes by that constant too. Both infima are real: because has no negative cycle, and by Fact 4.
Fact 5 (Dijkstra on ). For each , line L7 returns for every , with for the vertices not reachable from .
Proof. By Fact 4 all weights are nonnegative, and Dijkstra's algorithm is correct on graphs with nonnegative weights.
Theorem. If has a negative cycle, JOHNSON returns "negative cycle". Otherwise it returns a matrix with for all , where exactly when is not reachable from .
Proof. The first part is Fact 2. Otherwise, fix . If is not reachable from , Fact 5 gives , the lemma says this is the case exactly when , and line L8 keeps . If is reachable, Fact 5 and the lemma give
where and are real by Fact 3.
Termination. Bellman-Ford on does at most passes over its arcs. Line L5 does steps. Lines L6 to L8 run Dijkstra times, and each run ends after it extracts each vertex at most once, followed by steps of line L8. All loops are bounded, so JOHNSON terminates on every finite input.