Algorithm Search⌘K

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 AA be the grid before the call, o=A[s]o = A[s] the old colour and cc the new colour. Let WW be the region of ss: the cells reached from ss by a sequence of neighbouring cells that all have colour oo in AA. Write A′A' for the grid during the run. If o=co = c, line L2 returns at once, and the grid is unchanged, which is correct because recolouring WW with oo changes nothing. From now on o≠co \ne c.

Invariant. At the start of each iteration of the loop of line L5, and when the loop ends:

  1. each cell pp with A′[p]≠A[p]A'[p] \ne A[p] is in WW and has A′[p]=cA'[p] = c;
  2. each cell of WW either still has A′[p]=oA'[p] = o or has A′[p]=cA'[p] = c;
  3. each cell on the stack has A′[p]=cA'[p] = c, and each cell that has been recoloured is on the stack now or has been popped before.

Initialization. After lines L3 and L4, only ss is changed, s∈Ws \in W, and ss is on the stack. All three parts hold.

Maintenance. An iteration pops pp and, for each neighbour qq of pp with A′[q]=oA'[q] = o, sets A′[q]=cA'[q] = c and pushes qq. By part 3, A′[p]=c≠oA'[p] = c \ne o, so pp was recoloured, and by part 1, p∈Wp \in W. A neighbour qq with A′[q]=oA'[q] = o was not changed, because changed cells have colour c≠oc \ne o, so A[q]=oA[q] = o. Then qq is a neighbour of a cell of WW and has colour oo in AA, so q∈Wq \in W. Recolouring it to cc keeps parts 1 and 2, and pushing it keeps part 3.

Termination. Each push follows a change of one cell from oo to cc, and a cell of colour cc never has colour oo again, so at most ∣W∣|W| cells are pushed. Each iteration pops one cell, so the loop runs at most ∣W∣|W| times, and each iteration does at most 4 tests.

Lemma. When the loop ends, every cell of WW has colour cc.

Proof. Assume a cell of WW still has colour oo. Take a sequence s=p0,p1,…,pjs = p_0, p_1, \ldots, p_j of neighbouring cells of colour oo in AA that ends at such a cell, and let pip_i be its first cell with A′[pi]=oA'[p_i] = o at the end. Then i≥1i \ge 1, because ss was recoloured at line L3. The cell pi−1p_{i-1} has colour cc at the end, by the choice of ii 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 pip_i was tested at line L8. Colours only change from oo to cc, and pip_i has colour oo at the end, so it had colour oo at that test. Then line L9 recoloured it, which contradicts A′[pi]=oA'[p_i] = o at the end. □\square

Theorem. FLOOD-FILL(A,s,c)(A, s, c) terminates, and afterwards each cell of WW has colour cc and each other cell has its colour in AA.

Proof. Termination was shown above. By the lemma, all cells of WW have colour cc. By part 1, each cell whose colour changed is in WW, so each cell outside WW has its old colour. ■\blacksquare

Back to Flood fill