733. Flood Fill
Description
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Constraints
The length of
imageandimage[0]will be in the range[1, 50].The given starting pixel will satisfy
0 <= sr < image.lengthand0 <= sc < image[0].length.The value of each color in
image[i][j]andnewColorwill be an integer in[0, 65535].
Approach
Links
GeeksforGeeks
ProgramCreek
YouTube
Examples
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.
Solutions
/**
* Time complexity : O(N), where N is the number of pixels in the image.
* We might process every pixel.
* Space complexity : O(N), the size of the implicit call stack when calling dfs.
*/
class Solution {
private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int oldColor = image[sr][sc];
if(oldColor == newColor) {
return image;
}
image[sr][sc] = newColor;
for(int i = 0; i < 4; i++) {
int x = sr + dirs[i][0];
int y = sc + dirs[i][1];
if(x < 0 || x >= image.length || y < 0 || y >= image[0].length) {
continue;
}
if(image[x][y] != oldColor) {
continue;
}
floodFill(image, x, y, newColor);
}
return image;
}
}/**
* Time complexity : O(N), where N is the number of pixels in the image.
* We might process every pixel.
* Space complexity : O(N), the size of the implicit call stack when calling dfs.
*/
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if(image[sr][sc] != newColor) {
fill(image, sr, sc, image[sr][sc], newColor);
}
return image;
}
private void fill(int[][] image, int x, int y, int oldColor, int newColor) {
if(image[x][y] == oldColor) {
image[x][y] = newColor;
if(x > 0) fill(image, x-1, y, oldColor, newColor);
if(y+1 < image[0].length) fill(image, x, y+1, oldColor, newColor);
if(x+1 < image.length) fill(image, x+1, y, oldColor, newColor);
if(y > 0) fill(image, x, y-1, oldColor, newColor);
}
}
}Follow up
Last updated
Was this helpful?