The problem, in one line. Given a grid of colours, a starting cell and a new colour, repaint the starting cell and every cell joined to it by a chain of up, down, left or right steps that share its colour. LeetCode 733.
The tell. “Everything connected to this cell” on a grid. A grid is a graph where each cell has up to four neighbours, and “connected” means you can reach it by walking, so you walk.
The wrong first idea
Scan the whole grid and repaint every cell that has the old colour.
for r in range(len(image)):
for c in range(len(image[0])):
if image[r][c] == old:
image[r][c] = color
It repaints cells that are the right colour but sit in a different blob, on the far side of the grid. “Same colour” is not the question. “Same colour and reachable from the start” is.
The invariant
Keep a stack of cells still to look at. Painting a cell is also the visited mark, so no cell is ever pushed twice with work left to do.
flowchart LR A["start (1,1)<br/>old colour 1"] --> B["paint it 2<br/>push 4 neighbours"] B --> C["neighbour has colour 1?<br/>paint, push its neighbours"] C --> D["neighbour is 0 or 2?<br/>stop"]
The sentence that stays true every step: a cell is painted exactly when it has been reached through cells of the old colour. The walk dies at walls of any other colour and at the edge of the grid.
The solution
def flood_fill(image, sr, sc, color):
old = image[sr][sc]
if old == color: # already the new colour: nothing to do, and no way to mark visited
return image
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
if 0 <= r < len(image) and 0 <= c < len(image[0]) and image[r][c] == old:
image[r][c] = color # painting is the visited mark
stack += [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]
return image
print(flood_fill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2))
print(flood_fill([[0, 0, 0], [0, 0, 0]], 0, 0, 0))
print(flood_fill([[1, 0], [0, 1]], 0, 0, 5))
[[2, 2, 2], [2, 2, 0], [2, 0, 1]]
[[0, 0, 0], [0, 0, 0]]
[[5, 0], [0, 1]]
func floodFill(image [][]int, sr, sc, color int) [][]int {
old := image[sr][sc]
if old == color { // already the new colour: nothing to do, and no way to mark visited
return image
}
stack := [][2]int{{sr, sc}}
for len(stack) > 0 {
p := stack[len(stack)-1]
stack = stack[:len(stack)-1]
r, c := p[0], p[1]
if r >= 0 && r < len(image) && c >= 0 && c < len(image[0]) && image[r][c] == old {
image[r][c] = color // painting is the visited mark
stack = append(stack, [2]int{r + 1, c}, [2]int{r - 1, c}, [2]int{r, c + 1}, [2]int{r, c - 1})
}
}
return image
}
Same three calls print [[2 2 2] [2 2 0] [2 0 1]], [[0 0 0] [0 0 0]], [[5 0] [0 1]].
Complexity
- Time O(m·n): each cell is painted at most once, and each painted cell pushes four neighbours.
- Space O(m·n): in the worst case, one big blob, the stack holds a few cells per painted cell.
Traps
- Skipping the old-equals-new check. On an all-zero grid with new colour 0, painting never changes anything, so the cells are never “visited” and the loop runs forever.
- Using plain recursion on a large single-colour grid. A 1,000 by 1,000 blob goes a million calls deep and Python’s default limit stops you long before.
- Spreading diagonally. Only four directions count, so in
[[1, 0], [0, 1]]the far corner keeps its colour.
Next in the ladder
Number of Islands runs the same walk many times: instead of one start cell you are given, you scan the grid, and every fresh land cell you meet starts a new walk and a new count.