Proofs: Generic component-growing algorithm
These are the human proofs of Generic component-growing algorithm, at full length.
Component growing labels each component and builds a spanning forest full
This proof shows: correctness.
Let be an undirected graph with the lists , where an edge with is in both lists. Parallel edges and loops are allowed. Write for the set of vertices joined to by a path, and .
Lemma 1. Consider a call GROW that starts with and with no vertex labelled . After each step of the loop of line L3 these invariants hold:
(I1) Every is in , and following parent pointers from reaches through vertices of .
(I2) For each , the entries all lead to vertices of .
(I3) Each has , and .
Proof. After lines L1 and L2, and , so all three hold. Take a step with the vertex of line L4.
If line L5 removes , then , so (I3) holds for , and nothing else changes.
Otherwise line L6 reads and moves the pointer by one. If , the new entry leads into and (I2) holds. The label of cannot be a smaller value : by Lemma 2 applied to the earlier call, is a full component, , and is a neighbour of , so . If , line L8 puts into and into with and . Then because and is an edge, and the parent chain of is followed by the chain of , so (I1) holds. The entry just read leads to , so (I2) holds, and , so (I3) holds.
Lemma 2. The call stops, and then .
Proof. Each step either moves a pointer forward or removes a vertex from . A pointer moves at most times, a vertex enters only once (when it gets its label), and so the loop runs at most times.
When , (I3) gives for each , and (I2) then says that every neighbour of every vertex of is in . Let and let be a path. Since and is closed under neighbours, induction on gives , so . Thus , and (I1) gives .
Theorem. COMPONENTS returns labels with if and only if and lie in the same component, equal to the number of components, and parent pointers that form a spanning forest of with one tree for each component.
Proof. By induction over the loop of line L10, before the iteration for the labelled vertices are the union of the components of the vertices , and each value labels exactly one component. If , lies in one of these components and nothing changes. Otherwise lies in none of them, so no vertex of has a label, and by Lemma 2 the call labels exactly with the new value . So at the end each component has its own label and is their number.
Each vertex of gets exactly one parent, in line L8, and its parent got its label earlier. So the parent edges in have no cycle, they number , and by (I1) they join every vertex to . They form a spanning tree of , and over all components a spanning forest.
The proof does not use the rule of line L4, so it holds for every rule, which is the point of the generic algorithm.