Algorithms · Graphs & grids

Flood fill

Repaint a square and every connected square of its colour.

The problem

This is the paint-bucket tool. Starting at row r, column c, repaint that square and every square connected to it (up, down, left, right) that has the same colour. Return the picture.

flood([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2)[[2, 2, 2], [2, 2, 0], [2, 0, 1]]
flood([[0, 0, 0], [0, 0, 0]], 0, 0, 0)[[0, 0, 0], [0, 0, 0]]
Graphs & grids. Spread out in rings. Drop a stone in a pond: the ripple reaches everything one step away, then two steps…

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def flood(grid, r, c, color):take the picture, a start square and a new colour
old = grid[r][c]the colour we're replacing
if old == color:already that colour?
return gridnothing to do
def paint(r, c):paint one square, then its neighbours
if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == old:inside the picture and the old colour?
grid[r][c] = colorrepaint it
paint(r + 1, c)spread down…
paint(r - 1, c)…up…
paint(r, c + 1)…right…
paint(r, c - 1)…and left
paint(r, c)start spreading
return gridthe repainted picture

Now ask: what if there were a billion?

Paint programs, Photoshop’s magic wand and Minesweeper’s auto-reveal all flood-fill. A 12-megapixel photo would need 12 million nested calls, so real tools use a queue, or paint whole rows at a time.

Aim for O(n)🌱 warm-up

Think it through

A recursive fill on a 1000 × 1000 picture of one colour. What goes wrong?

  • Nothing
  • Python’s recursion limit (about 1,000 deep) is hit
Show the answer

Python’s recursion limit (about 1,000 deep) is hit. Each call waits for the next, and a snake-shaped area can be a million calls deep. Python stops at about 1,000.

What can replace the recursion?

  • Your own to-do list of squares
  • Painting row by row only
Show the answer

Your own to-do list of squares. A queue of squares to visit: take one out, paint its matching neighbours, add them. That’s breadth-first search, and it only grows with the picture, not with Python’s limit.

Stuck? 3 nudges, smallest first
  1. Recursion remembers every square it’s in the middle of. Python only lets that pile get about 1,000 deep.
  2. Use your own to-do list of squares instead: a queue. Take one out, paint its neighbours, add them to the queue.
  3. Paint the start, put it in a deque. While the queue isn’t empty: popleft(), and for each matching neighbour, paint it and append it.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
from collections import dequea queue that's quick at both ends
def flood(grid, r, c, color):take the picture, a start square and a new colour
old = grid[r][c]the colour we're replacing
if old == color:already that colour?
return gridnothing to do
grid[r][c] = colorpaint the start square
queue = deque([(r, c)])squares whose neighbours we still need to check
while queue:while the ripple is still spreading
r, c = queue.popleft()the oldest square in the queue
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):its four neighbours
nr, nc = r + dr, c + dcthe neighbour's position
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == old:inside, and the old colour?
grid[nr][nc] = colorpaint it
queue.append((nr, nc))and check its neighbours later
return gridthe repainted picture

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with graphs & grids