Skip to problem
←

Flood Fill

Easy 0 attempts

You're given an m x n grid of integers called image, where each value is a pixel's color. Starting from a given pixel at (sr, sc), repaint it along with every pixel reachable from it through 4-directional moves (up/down/left/right) that share the pixel's original color, changing them all to the new color. Return the resulting grid.

Function contract

image is a nonempty rectangular integer grid. sr and sc are valid zero-based row and column indices; color is the replacement color.

Output: Return the image with only the source pixel’s four-connected, original-color region repainted. You may modify image in place.

Example 1

Input
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1
sc = 1
color = 2
Output
[[2,2,2],[2,2,0],[2,0,1]]

Explanation: The bottom-right 1 is only diagonally adjacent to the filled region, so it remains unchanged.

Example 2

Input
image = [[1]]
sr = 0
sc = 0
color = 1
Output
[[1]]
Constraints
  • 1 <= m, n <= 50
  • 0 <= image[i][j], color < 2^16
  • image has m rows and n columns; 0 <= sr < m and 0 <= sc < n.
Topics

Iterative Flood Fill

Record the source color. If it already equals the replacement, return immediately. Otherwise, repaint each pixel when adding it to the stack so it cannot be added twice. Explore only its four orthogonal neighbors.

javascript
function floodFill(image, sr, sc, color) {
  const original = image[sr][sc];
  if (original === color) return image;
  const stack = [[sr, sc]];
  image[sr][sc] = color;
  const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  while (stack.length) {
    const [r, c] = stack.pop();
    for (const [dr, dc] of directions) {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nr >= image.length || nc < 0 || nc >= image[0].length) continue;
      if (image[nr][nc] !== original) continue;
      image[nr][nc] = color;
      stack.push([nr, nc]);
    }
  }
  return image;
}

Time: O(m × n) worst case | Space: O(m × n) for the explicit stack.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript