sagelearnai

Flood Fill

Difficulty: Easy · Pattern: Graphs (BFS / DFS) · LeetCode #733

Starting from pixel (sr, sc), recolor that pixel and every pixel 4-directionally connected to it that has the same original color, to color. Return the modified image.

Examples

text
image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
→ [[2,2,2],[2,2,0],[2,0,1]]     (the bottom-right 1 is not connected)
image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0  →  unchanged

Hints

  1. This is the "paint bucket" tool: a connected-component traversal on a grid.
  2. Watch the edge case where color equals the original color. Without a check you'd revisit pixels forever.

Approach

Remember orig = image[sr][sc]. If orig == color, return immediately (nothing changes, and it would loop forever). Otherwise DFS with an explicit stack: pop a cell, skip it if it's out of bounds or not orig, recolor it, and push its 4 neighbors. Recoloring doubles as the visited marker, so no extra set is needed.

Complexity

Time: O(R·C). Space: O(R·C) worst-case stack.

Python solution
def floodFill(image, sr, sc, color):
    orig = image[sr][sc]
    if orig == color:
        return image
    R, C = len(image), len(image[0])
    stack = [(sr, sc)]
    while stack:
        r, c = stack.pop()
        if 0 <= r < R and 0 <= c < C and image[r][c] == orig:
            image[r][c] = color
            stack += [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]
    return image
JavaScript solution
function floodFill(image, sr, sc, color) {
  const orig = image[sr][sc];
  if (orig === color) return image;
  const R = image.length, C = image[0].length, stack = [[sr, sc]];
  while (stack.length) {
    const [r, c] = stack.pop();
    if (r < 0 || c < 0 || r >= R || c >= C || image[r][c] !== orig) continue;
    image[r][c] = color;
    stack.push([r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]);
  }
  return image;
}