Proofs: Warshall's algorithm
These are the human proofs of Warshall's algorithm, at full length.
Warshall's algorithm computes the transitive closure full
This proof shows: correctness, termination.
Let be a directed graph with , where parallel arcs and loops are allowed. A walk from to of length is a sequence with for each ; its inner vertices are . For , let
We view as a set of pairs: when . Write for the value of just before round of line L2, so that is the value returned by line L6.
Lemma 1. , as a set of pairs, and is the transitive closure .
Proof. A walk with no inner vertex has length 1 and is an arc, and an arc is such a walk. Every inner vertex is in , so contains every pair joined by a walk of length at least 1.
Lemma 2. , and if and , then .
Proof. The first claim is clear. For the second, join a walk from to and a walk from to , both with inner vertices below . The result is a walk of length at least 2 from to whose inner vertices are those of the two walks and , all in .
Lemma 3. If , then , or both and .
Proof. Take a walk with inner vertices in . If is not an inner vertex, . Else let be the first inner vertex equal to and the last, with . The walk goes from to , has length , and its inner vertices are inner vertices of the whole walk other than , so they are below . So . In the same way shows .
Lemma 4 (one round). If , then .
Proof. During round , line L5 adds to row the pairs with in the current row , for those with in the current . We first show that row does not change in round . A change of row can only happen when line L5 runs with , and it then takes the OR of row with itself. So throughout round , row equals row of .
. We show that holds throughout round . It holds at the start, as . Suppose it holds before some run of line L5 with row , where . Each pair it adds is with in row , so . Also , and by Lemma 3 applied with , either , or and ; in both cases . Lemma 2 gives .
. Let . Entries never change from 1 to 0, so if it is in . Else, by Lemma 3, and . When line L3 reaches row in round , is still in , so line L4 succeeds, and is in row , which has not changed. So line L5 sets .
Theorem. WARSHALL stops, after rounds of steps each, and returns with exactly when has a walk of length at least 1 from to .
Proof. The loops of lines L2 and L3 have steps each, and line L5 is a finite row operation, so the algorithm stops. Line L1 sets by Lemma 1, as parallel arcs set the same entry. By Lemma 4 and induction on , , which is by Lemma 1.
Remark on the implementation. The Python code reads row once, as rk, before the loop over . This is the same as reading it at each step, because, as shown in Lemma 4, row does not change in round .