LeetCode733
class Solution {
boolean is[][];
int value;
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
value = image[sr][sc];
is = new boolean[image.length][];
for(int i = 0; i < image.length; i++) {
is[i] = new boolean[image[i].length];
}
dfs(image, sr, sc, newColor);
return image;
}
// 上下左右分别递归没啥说的,主要说的就是递归时的越界问题
// 由于边界是0和length-1,这个时候是合法的,可以操作,也允许递归,但是递归之后的值就不合法了
// 因此这时就需要将越过边界的值给踢出
// 注意这里边界的地方可以向下走,递归也允许,只是递归之后的值不允许了
public void dfs(int[][] image, int x, int y, int newColor) {
if(x < 0 || y < 0 || x >= image.length || y >= image[x].length || image[x][y] != value || is[x][y]){
return;
}
image[x][y] = newColor;
is[x][y] = true;
dfs(image, x - 1, y, newColor);
dfs(image, x, y - 1, newColor);
dfs(image, x + 1, y, newColor);
dfs(image, x, y + 1, newColor);
}
}
dfs二维数组
最新推荐文章于 2023-05-30 11:47:30 发布