代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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:
image
and image[0]
will be in the range [1, 50]
.0 <= sr < image.length
and 0 <= sc < image[0].length
.image[i][j]
and newColor
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)
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。