LeetCode #733 Easy

Flood Fill

Paint-bucket: recolor the connected region of same-colored pixels around (sr, sc).

dfsbfsmatrix
Open on LeetCode ↗
02

Intuition

It's DFS/BFS on the grid: from the start pixel, spread to 4-neighbours sharing the original color, repainting as you go. Repainting doubles as the visited-marker.

How to spot this pattern

Identical machinery to counting islands, minus the outer scan — one component, one flood. The reusable shape is: validate bounds and the match condition at the top of the recursive function, mark on entry, then recurse in all four directions. Every grid-flood problem is this function with a different mark and a different match test.

03

Approach

1

Remember the original color

Only pixels matching it spread the fill; the new color is the paint.

2

DFS with bounds checks

Recurse on 4 neighbours inside the grid with the old color. Repaint before recursing to avoid revisits.

3

The self-fill trap

If newColor == oldColor the recursion never terminates — return immediately in that case.

04

Solution & live demo

1class Solution:
2 def floodFill(self, image, sr, sc, color):
3 old = image[sr][sc]
4 if old == color: return image
5 R, C = len(image), len(image[0])
6 def fill(r, c):
7 if 0 <= r < R and 0 <= c < C and image[r][c] == old:
8 image[r][c] = color
9 fill(r+1, c); fill(r-1, c); fill(r, c+1); fill(r, c-1)
10 fill(sr, sc)
11 return image
05

Common pitfalls

Not returning early when the new colour equals the old

✗ Wrong
old = image[sr][sc]
def fill(r, c): ...
✓ Right
old = image[sr][sc]
if old == color: return image

Painting a cell its existing colour doesn't change it, so the image[r][c] == old test stays true forever and neighbours recurse into each other until the stack overflows. The guard is what guarantees progress — this is the single most common way to hang this problem.

Matching against the starting cell's live value

✗ Wrong
if image[r][c] == image[sr][sc]:
✓ Right
old = image[sr][sc]
if image[r][c] == old:

The origin gets repainted on the very first step, so the comparison target changes mid-traversal and the fill stops after one cell. Capture the original colour before any mutation.

Filling diagonally

✗ Wrong
fill(r+1, c+1); fill(r-1, c-1)
✓ Right
fill(r+1, c); fill(r-1, c); fill(r, c+1); fill(r, c-1)

The problem defines connectivity as 4-directional. Adding diagonals bleeds the fill across regions that only touch at a corner and are meant to stay separate.

06

Edge cases

New color equals old color

Early return — otherwise infinite loop.

Start pixel isolated

Only it changes; neighbours differ in color.

07

Complexity

Time
O(R·C)
Space
O(R·C)
Each pixel painted once; recursion depth worst-case.