链接:https://leetcode-cn.com/problems/flood-fill/
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
示例 1:
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
注意:
image 和 image[0] 的长度在范围 [1, 50] 内。
给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。
image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。
这本来是一道很简单的DFS问题,却因为一个点卡了一个半小时
先上一直过不了的代码
class Solution {
public:
void dfs(vector<vector<int>>& image, int x, int y, int oldColor, int newColor)
{
cout<<x<<y<<" ";
if(image[x][y] == oldColor)
image[x][y] = newColor;
else return;
int dis[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
for(int i = 0; i < 4; i++)
{
int xx = x + dis[i][0];
int yy = y + dis[i][1];
cout<<xx<<yy<<" ";
if(0 <= xx && xx < image.size() && 0 <= yy && yy < image[0].size())
{
dfs(image, xx, yy, oldColor, newColor);
cout<<xx<<yy<<endl;
}
}
return;
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
// int len1 = image.size();
// int len2 = image[0].size();
int oldColor = image[sr][sc];
dfs(image, sr, sc, oldColor, newColor);
return image;
}
};
代码的问题在于,如果image[sr][sc]原来的颜色等于newColor的话,会出现死循环。
上样例:[[0,0,0],[0,1,1]] 1 1 1
即图案为 0 0 0
0 1 1
起点是(1,1),根据代码,(1,1)->(2, 1)(不符合条件)
->(1, 2)->(2, 2)(不符合条件)
->(1, 3)(不符合条件)
->(0, 2)(不符合条件)
->(1, 1)
这时 若newColor和初始颜色不相等的话,就没有问题,但此时,更新过的imag[1][1]仍然满足等于oldColor的条件,这就会导致一直重复上述步骤,造成死循!!!!!!!!因此我们在这个特殊情况时,直接返回image,不用进行dfs。
class Solution {
public:
void dfs(vector<vector<int>>& image, int x, int y, int oldColor, int newColor)
{
// cout<<x<<y<<" ";
if(image[x][y] == oldColor)
image[x][y] = newColor;
else return;
int dis[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
for(int i = 0; i < 4; i++)
{
int xx = x + dis[i][0];
int yy = y + dis[i][1];
// cout<<xx<<yy<<" ";
if(0 <= xx && xx < image.size() && 0 <= yy && yy < image[0].size())
{
dfs(image, xx, yy, oldColor, newColor);
// cout<<xx<<yy<<endl;
}
}
return;
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
// int len1 = image.size();
// int len2 = image[0].size();
int oldColor = image[sr][sc];
if(oldColor == newColor) return image;
dfs(image, sr, sc, oldColor, newColor);
return image;
}
};
只需要加上倒数第五句话。