733. Flood Fill
Asked at 12Amazon54Apple46Microsoft43Google31Bloomberg30Meta26Criteo78Qualtrics69Uber50Visa39Capital One35tcs27
Problem
Starting at pixel (sr, sc), recolour it and every pixel connected to it (up, down, left, right) through pixels of the same original colour with color, and return the image.
Example: 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]]
DFS/BFS from the start cell through 4-neighbours that have the original color, recoloring as you go. If the new color equals the original, return immediately — otherwise the search never terminates (recolored cells still match).
Complexity: O(R·C).
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
old = image[sr][sc]
if old == color:
return image
R, C = len(image), len(image[0])
image[sr][sc] = color
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == old:
image[nr][nc] = color
stack.append((nr, nc))
return image
assert Solution().floodFill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2) == [[2, 2, 2], [2, 2, 0], [2, 0, 1]]
assert Solution().floodFill([[0, 0, 0], [0, 0, 0]], 0, 0, 0) == [[0, 0, 0], [0, 0, 0]]
assert Solution().floodFill([[0, 0, 0], [0, 1, 1]], 1, 1, 1) == [[0, 0, 0], [0, 1, 1]]
assert Solution().floodFill([[1]], 0, 0, 3) == [[3]]
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
int old = image[sr][sc];
if (old != color) fill(image, sr, sc, old, color);
return image;
}
private void fill(int[][] g, int r, int c, int old, int color) {
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != old) return;
g[r][c] = color;
fill(g, r + 1, c, old, color);
fill(g, r - 1, c, old, color);
fill(g, r, c + 1, old, color);
fill(g, r, c - 1, old, color);
}
}
func floodFill(image [][]int, sr int, sc int, color int) [][]int {
old := image[sr][sc]
if old == color {
return image
}
R, C := len(image), len(image[0])
image[sr][sc] = color
st := [][2]int{{sr, sc}}
for len(st) > 0 {
p := st[len(st)-1]
st = st[:len(st)-1]
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr >= 0 && nr < R && nc >= 0 && nc < C && image[nr][nc] == old {
image[nr][nc] = color
st = append(st, [2]int{nr, nc})
}
}
}
return image
}