Proofs: Whatever-first search
These are the human proofs of Whatever-first search, at full length.
Whatever-first search marks exactly the reachable vertices and builds a tree full
This proof shows: correctness, termination.
Let be a directed or undirected graph, where an undirected edge is in both adjacency lists, and let . The bag may follow any discipline: we only use that TAKE removes and returns some item that is in . Let be the set of vertices reachable from .
Lemma 1 (pairs come from marked vertices). At each moment, each pair in is either or has marked and .
Proof. The pair is put at line L2. All other pairs are put at line L7, as with , right after line L6 marked . Marks are never removed.
Lemma 2 (each vertex is marked once). Line L6 runs at most one time for each vertex, and line L7 scans each list at most one time.
Proof. Line L6 runs for only after line L5 found unmarked, and it marks , which then stays marked. Line L7 runs only right after line L6.
Termination. By Lemma 2, line L7 runs at most times, so at most pairs are ever put. Each iteration of the loop of line L3 takes one pair, so there are at most that many iterations, and the loop ends with empty.
Lemma 3 (marked means reachable). Each marked vertex is in , and if is marked, then was marked before and .
Proof. By induction on the order of marking. The first pair taken is , because it is the only pair until a vertex is marked, so is marked first, with , and . If is marked later by the pair , then this pair is not , since was already marked when it could be taken again; by Lemma 1, is marked and . Line L6 sets , and was marked before . By the induction hypothesis , so too.
Lemma 4 (reachable means marked). When the algorithm ends, each vertex of is marked.
Proof. Assume that some is unmarked at the end, and let be a path in . The vertex is marked, so there is a first unmarked vertex on the path, with . The vertex is marked, so line L7 ran for it and put the pair , because . The loop ends only when is empty, so this pair was taken at some step. At that step, line L5 either found marked or marked it. Either way is marked at the end, which contradicts its choice.
Theorem. WHATEVER-FIRST-SEARCH terminates for every discipline of the bag. When it ends, exactly for , and the edges for form a tree rooted at that spans , in which each path from is a path of .
Proof. Termination was shown above. Lemmas 3 and 4 give the marked set. For the tree, take and follow . By Lemma 3, each step goes to a vertex that was marked strictly earlier, along an edge of read backwards, so no vertex repeats, and the chain ends at the only marked vertex with parent NIL, which is , because line L6 sets for each . Each has exactly one parent, so the edges connect all of to without a cycle, and they form a tree rooted at . Its path from to is the chain read forwards, a path of .