Problems
Flood Fill
Easy·Tagsgraphdfsmatrixrecursion
Problem Statement
An image is represented by an `m x n` integer grid `image` where `image
[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a flood fill on the image starting from the pixel `image[sr][sc]`.
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return the modified image after performing the flood fill.Examples
Example 1
Input
image: [[1, 1, 1], [1, 1, 0], [1, 0, 1]], sr: 1, sc: 1, color: 2Grid
Output
"[[2, 2, 2], [2, 2, 0], [2, 0, 1]]"Why
From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Example 2
Input
image: [[0, 0, 0], [0, 0, 0]], sr: 0, sc: 0, color: 0Grid
Output
"[[0, 0, 0], [0, 0, 0]]"Why
The starting pixel is already colored 0, so no changes are made to the image.
Constraints
- •m == image.length
- •n == image[i].length
- •1 <= m, n <= 50
- •0 <= image[i][j], color < 2^16
- •0 <= sr < m
- •0 <= sc < n
Hints
Stuck? Reveal a nudge toward the right pattern, one step at a time.
Hint 1
Think of the 2D array as a graph. Each cell is a node, and the edges connect it to its top, bottom, left, and right neighbors.
Hint 2
Before you start, record the original color of the starting pixel. You only want to spread to neighboring pixels if they match this exact original color.
Hint 3
Be careful of an infinite loop! What happens if the `color` you are changing it to is exactly the same as the original color? You need to handle this edge case up front.
Hint 4
Use Depth-First Search (DFS) or Breadth-First Search (BFS). In your recursive function, check if the current indices are out of bounds (less than 0 or greater than row/col limits) or if the current cell doesn't match the original color.