AceYourInterviews
Checking sign-in…

95. Flood Fill

CoreUse the changed color as a discovery mark only when it differs from the original

Starting at the seed, recolor every cell reachable through orthogonal moves while staying on the seed's original color. Stop at cells of a different original color.

Only the connected component containing the seed changes. If the requested color already matches, avoid repeatedly revisiting unchanged cells.

Example 1

Input

image=[[1,1,0],[1,0,0],[2,2,1]], seed=(0,0), color=7

Output

same image; [[7,7,0],[7,0,0],[2,2,1]]

Explanation: The disconnected bottom-right 1 is outside the seed component.

Example 2

Input

image=[[MIN,0],[MIN,MAX]], seed=(0,0), color=MIN

Output

same unchanged image

Explanation: The no-op guard is essential when color would otherwise fail to distinguish discovered cells.

Constraints

  • 0 <= image.length <= 105
  • 0 <= total image cells <= 105
  • All rows have equal length and are non-null.
  • The seed coordinate must lie inside the image. Pixel values and replacement color are signed 32-bit integers.
Hints
Hint 1

Which equal-colored cells are actually connected to the seed?

Hint 2

A different replacement color can act as the visited mark.

Hint 3

Validate ownership, guard equal colors, then paint each coordinate before enqueueing it.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Only the original seed component is painted

[[1,1,0],[1,0,0],[2,2,1]]
0
0
7
[[7,7,0],[7,0,0],[2,2,1]]