Flood Fill

easy

You are given an R × C image where image[i][j] is the pixel's colour, a starting pixel (sr, sc), and a newColor. Perform a flood fill: starting at (sr, sc), repaint that pixel and every pixel 4-directionally connected to it that shares the same original colour with newColor. Return the modified image.

Hints

Capture the start pixel's original colour before you overwrite it.
Spread 4-directionally to neighbours that equal the original colour, repainting to newColor.
If newColor already equals the original colour, return immediately — otherwise you loop forever.

Common doubts

Recolouring is how you mark visited. If newColor equals the original, repainted cells look unvisited, so the traversal never terminates.
Both O(R·C) and identical output; BFS avoids stack overflow on a large single-colour region.
Same flood-fill core; islands counts regions, flood fill recolours one region from a given start.

Interview follow-ups

Add the four diagonal directions to the neighbour set.
Same algorithm; often with a colour tolerance instead of exact match.

Fun facts

  • LeetCode 733 — the literal paint-bucket algorithm.
  • The equal-colour short-circuit is the single most common bug in flood fill.

Asked at

AmazonMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
The connected block of 1s containing (1,1) is repainted to 2.
Example 2
Input: image = [[7]], sr = 0, sc = 0, newColor = 7
Output: [[7]]
newColor equals the start colour, so the image is unchanged.
Constraints

- 1 <= R, C <= 50 - 0 <= image[i][j], newColor <= 65535 - 0 <= sr < R - 0 <= sc < C

Solve this problem →