Flood Fill

25 min · floodFill()

One tap in a paint app can recolor a winding patch without touching the pixels right beside it in another patch. Your code gets to decide exactly where that color travels.

You're given a rectangular image image, a starting position (sr, sc), and a new color. A region is the set of pixels you can reach from the start by moving up, down, left, or right while staying on the start pixel's original color. Recolor every pixel in that region, then return the image.

A few ground rules:

  • Diagonal pixels don't connect.
  • Pixels with any color other than the start pixel's original color form a boundary.
  • If color already matches the original color, return the image unchanged.

Constraints

  • 1 <= image.length <= 50
  • 1 <= image[r].length <= 50
  • Every row has the same length.
  • 0 <= image[r][c], color <= 65_536
  • 0 <= sr < image.length
  • 0 <= sc < image[0].length

Hints

Remember the first color

Save image[sr][sc] before changing anything. Every later decision compares a neighbor with that original color, not with the new one.

Walk the region

Treat each matching pixel as a node with at most four neighbors. A stack or queue can carry you through every reachable matching pixel.

Handle the no-op first

If the old and new colors match, stop immediately. Otherwise, recoloring a pixel can double as marking it visited.

Follow-up

Could you write the traversal iteratively so a long, narrow region never depends on your language's recursion limit?

Visible cases

Examples

Example 1

ready
Input
image = [
  [
    1,
    1,
    1
  ],
  [
    1,
    1,
    0
  ],
  [
    1,
    0,
    1
  ]
]
sr = 1
sc = 1
color = 2
Expected
[
  [
    2,
    2,
    2
  ],
  [
    2,
    2,
    0
  ],
  [
    2,
    0,
    1
  ]
]
Why
the start's connected 1-region changes to 2; the diagonal 1 stays put

Example 2

ready
Input
image = [
  [
    0,
    0,
    0
  ],
  [
    0,
    1,
    1
  ]
]
sr = 1
sc = 1
color = 1
Expected
[
  [
    0,
    0,
    0
  ],
  [
    0,
    1,
    1
  ]
]
Why
the requested color already matches, so the image is unchanged

Example 3

ready
Input
image = [
  [
    3,
    3,
    8,
    8
  ],
  [
    3,
    8,
    8,
    3
  ],
  [
    3,
    3,
    3,
    3
  ]
]
sr = 0
sc = 2
color = 5
Expected
[
  [
    3,
    3,
    5,
    5
  ],
  [
    3,
    5,
    5,
    3
  ],
  [
    3,
    3,
    3,
    3
  ]
]
Why
only the connected patch of 8s is recolored

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite