Flood Fill

Recolor a connected region in a grid — DFS or BFS from the start cell.

Easy
Time O(m * n) Space O(m * n)
LeetCode
3 min read
backtracking grid dfs

Problem#

Starting from (sr, sc), replace the color of every 4-connected cell of the same starting color with newColor.

Examples#

  • image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2[[2,2,2],[2,2,0],[2,0,1]]

Constraints#

  • 1 <= m, n <= 50.

Approach#

DFS, skipping if already recolored or different color.

Solution#

Flood Fill
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
int orig = image[sr][sc];
if (orig == color) return image;
function<void(int,int)> dfs = [&](int r, int c) {
if (r < 0 || r >= (int)image.size() || c < 0 || c >= (int)image[0].size() || image[r][c] != orig) return;
image[r][c] = color;
dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1);
};
dfs(sr, sc);
return image;
}
};

Editorial#

The orig == color guard prevents infinite recursion when no work is needed. Recoloring the visited cell serves dual duty: marks visited and produces the output.

Complexity#

  • Time: O(m * n).
  • Space: O(m * n) recursion worst case.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.