题目:
解决方法:
方法1:广度优先搜索
从坐标(sr,sc)往上下左右寻找image[sr][sc]这个颜色的坐标,然后把找到的坐标存到一个数组中,之后再从这个数组中的坐标再寻找上下左右寻找,直到这个数组全部被找完。
这里面是有图,学过图的话,看这个比较好理解。
深度优先搜索(dfs)和广度优先搜索(bfs)_猫弦920的博客-优快云博客
其次是,我们要知道,往上下左右寻找,有些坐标是没有左边,或者右边的。我们看下图:
坐标为(0,y)是没有上边;坐标为(3,y) 是没有下边; 坐标为(x,0) 是没有左边; 坐标为(x,3) 是没有右边。这里的的横坐标的3应该是image.length-1,纵坐标的3是image[0].length-1,由此我们有了四个判断条件。
还要知道,当newColor 和 image[sr][sc] 的颜色相同时候,直接返回 image 这样速度会快很多。(这里很重要,不然就超时了)
代码:
var floodFill = function (image, sr, sc, newColor) {
let visited = [[sr, sc]];
let oldColor = image[sr][sc];
image[sr][sc] = newColor;
if (newColor == oldColor) {
return image;
}
while (visited.length != 0) {
let current = visited.pop();
let x = current[0];
let y = current[1];
// 上
if (x > 0 && image[x - 1][y] == oldColor) {
visited.push([x - 1, y]);
image[x - 1][y] = newColor;
}
// 下
if (x < image.length - 1 && image[x + 1][y] == oldColor) {
visited.push([x + 1, y]);
image[x + 1][y] = newColor;
}
// 左
if (y > 0 && image[x][y - 1] == oldColor) {
visited.push([x, y - 1]);
image[x][y - 1] = newColor;
}
// 右
if (y < image[0].length - 1 && image[x][y + 1] == oldColor) {
visited.push([x, y + 1]);
image[x][y + 1] = newColor;
}
}
return image;
};
方法2:深度优先搜索
从坐标(sr,sc)往上下左右寻找 image[sr][sc]这个颜色的坐标,假如我们找到了,这个坐标为(x,y),那么我们先找这个(x,y)的上下左右,直到上下左右没有相同的颜色之后,再返回上一个坐标接着往下找,直到最开始那个坐标的上下左右没有相同的颜色为止。
代码:
var floodFill = function (image, sr, sc, newColor) {
if (image[sr][sc] == newColor) return image;
const dfs = (image, x, y, oldColor, newColor) => {
// 上
if (x > 0 && image[x - 1][y] == oldColor) {
image[x - 1][y] = newColor;
dfs(image, x - 1, y, oldColor, newColor);
}
// 下
if (x < image.length - 1 && image[x + 1][y] == oldColor) {
image[x + 1][y] = newColor;
dfs(image, x + 1, y, oldColor, newColor);
}
// 左
if (y > 0 && image[x][y - 1] == oldColor) {
image[x][y - 1] = newColor;
dfs(image, x, y - 1, oldColor, newColor);
}
// 右
if (y < image[0].length - 1 && image[x][y + 1] == oldColor) {
image[x][y + 1] = newColor;
dfs(image, x, y + 1, oldColor, newColor);
}
return image;
}
dfs(image, sr, sc, image[sr][sc], newColor);
image[sr][sc] = newColor;
return image;
};