Proofs: Flood fill
These are the human proofs of Flood fill, at full length.
Flood fill recolours exactly the region of the seed full
This proof shows: correctness, termination.
Let be the grid before the call, the old colour and the new colour. Let be the region of : the cells reached from by a sequence of neighbouring cells that all have colour in . Write for the grid during the run. If , line L2 returns at once, and the grid is unchanged, which is correct because recolouring with changes nothing. From now on .
Invariant. At the start of each iteration of the loop of line L5, and when the loop ends:
- each cell with is in and has ;
- each cell of either still has or has ;
- each cell on the stack has , and each cell that has been recoloured is on the stack now or has been popped before.
Initialization. After lines L3 and L4, only is changed, , and is on the stack. All three parts hold.
Maintenance. An iteration pops and, for each neighbour of with , sets and pushes . By part 3, , so was recoloured, and by part 1, . A neighbour with was not changed, because changed cells have colour , so . Then is a neighbour of a cell of and has colour in , so . Recolouring it to keeps parts 1 and 2, and pushing it keeps part 3.
Termination. Each push follows a change of one cell from to , and a cell of colour never has colour again, so at most cells are pushed. Each iteration pops one cell, so the loop runs at most times, and each iteration does at most 4 tests.
Lemma. When the loop ends, every cell of has colour .
Proof. Assume a cell of still has colour . Take a sequence of neighbouring cells of colour in that ends at such a cell, and let be its first cell with at the end. Then , because was recoloured at line L3. The cell has colour at the end, by the choice of and part 2. By part 3, it was pushed, and since the stack is empty at the end, it was popped. When it was popped, its neighbour was tested at line L8. Colours only change from to , and has colour at the end, so it had colour at that test. Then line L9 recoloured it, which contradicts at the end.
Theorem. FLOOD-FILL terminates, and afterwards each cell of has colour and each other cell has its colour in .
Proof. Termination was shown above. By the lemma, all cells of have colour . By part 1, each cell whose colour changed is in , so each cell outside has its old colour.