Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.
Example1:
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.
Note:
- The length of
image
andimage[0]
will be in the range[1, 50]
. - The given starting pixel will satisfy
0 <= sr < image.length
and0 <= sc < image[0].length
. - The value of each color in
image[i][j]
andnewColor
will be an integer in[0, 65535]
.
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int oldColor = image[sr][sc];
dfs(image, sr, sc, oldColor, newColor);
return image;
}
private void dfs(int[][] image, int sr, int sc, int oldColor, int newColor) {
if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length) {
return;
}
int color = image[sr][sc];
if (color != newColor && color == oldColor) {
image[sr][sc] = newColor;
// up down left right
dfs(image, sr, sc + 1, oldColor, newColor);
dfs(image, sr, sc - 1, oldColor, newColor);
dfs(image, sr + 1, sc, oldColor, newColor);
dfs(image, sr - 1, sc, oldColor, newColor);
}
}
}