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]
.
DFS.
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
def dfs(i, j, oc, nc):
if i < 0 or i >= len(image) or j < 0 or j >= len(image[0]) or image[i][j] != oc or image[i][j] == nc:
return
image[i][j] = nc
for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
dfs(i + x, j + y, oc, nc)
dfs(sr, sc, image[sr][sc], newColor)
return image
class Solution {
private int[][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
dfs(image, sr, sc, image[sr][sc], newColor);
return image;
}
private void dfs(int[][] image, int i, int j, int oc, int nc) {
if (i < 0 || i >= image.length || j < 0 || j >= image[0].length || image[i][j] != oc || image[i][j] == nc) {
return;
}
image[i][j] = nc;
for (int[] dir : dirs) {
dfs(image, i + dir[0], j + dir[1], oc, nc);
}
}
}
class Solution {
public:
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
dfs(image, sr, sc, image[sr][sc], newColor);
return image;
}
void dfs(vector<vector<int>>& image, int i, int j, int oc, int nc) {
if (i < 0 || i >= image.size() || j < 0 || j >= image[0].size() || image[i][j] != oc || image[i][j] == nc) return;
image[i][j] = nc;
for (auto& dir : dirs) dfs(image, i + dir[0], j + dir[1], oc, nc);
}
};
func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
dfs(image, sr, sc, image[sr][sc], newColor)
return image
}
func dfs(image [][]int, i, j, oc, nc int) {
if i < 0 || i >= len(image) || j < 0 || j >= len(image[0]) || image[i][j] != oc || image[i][j] == nc {
return
}
image[i][j] = nc
dirs := [4][2]int{{0, -1}, {0, 1}, {1, 0}, {-1, 0}}
for _, dir := range dirs {
dfs(image, i+dir[0], j+dir[1], oc, nc)
}
}