733. Flood Fill
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel 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.// DFS
void helper(vector<vector<int> >& image, int i, int j, int color, int newColor) {
if (i < 0 || i >= image.size() || j < 0 || j >= image[0].size() || image[i][j] != color) return;
image[i][j] = newColor;
helper(image, i + 1, j, color, newColor);
helper(image, i - 1, j, color, newColor);
helper(image, i, j + 1, color, newColor);
helper(image, i, j - 1, color, newColor);
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // time: O(m * n); space: O(m * n)
if (image[sr][sc] == newColor) return image;
helper(image, sr, sc, image[sr][sc], newColor);
return image;
}Last updated