难度简单326收藏分享切换为英文接收动态反馈
有一幅以 m x n
的二维整数数组表示的图画 image
,其中 image[i][j]
表示该图画的像素值大小。
你也被给予三个整数 sr
, sc
和 newColor
。你应该从像素 image[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,因为它不是在上下左右四个方向上与初始点相连的像素点。
示例 2:
输入: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2 输出: [[2,2,2],[2,2,2]]
提示:
m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], newColor < 216
0 <= sr < m
0 <= sc < n
通过次数108,858提交次数187,366
题解:广度搜索需要一个队列,队列存储坐标,所以我新建了一个结构体来保存位置点。需要注意的一点就是,当指定点已经是newcolor之后,直接返回即可,否则就是死循环。
class Solution {
struct T_POS
{
int x;
int y;
};
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int curvalue=image[sr][sc];
if(newColor == curvalue)
return image;
int n=image.size()-1;
int m=image[0].size()-1;
queue<T_POS> qpos;
T_POS tempos;
tempos.x=sr;
tempos.y=sc;
image[tempos.x][tempos.y]=newColor;
qpos.push(tempos);
while(!qpos.empty())
{
T_POS temposNew;
temposNew=qpos.front();
qpos.pop();
int x=temposNew.x;
int y=temposNew.y;
if(image[min(x+1,n)][y]==curvalue)
{
tempos.x=min(x+1,n);
tempos.y=y;
image[tempos.x][tempos.y]=newColor;
qpos.push(tempos);
}
if(image[max(x-1,0)][y]==curvalue)
{
tempos.x=max(x-1,0);
tempos.y=y;
image[tempos.x][tempos.y]=newColor;
qpos.push(tempos);
}
if(image[x][max(y-1,0)]==curvalue)
{
tempos.x=x;
tempos.y=max(y-1,0);
image[tempos.x][tempos.y]=newColor;
qpos.push(tempos);
}
if(image[x][min(y+1,m)]==curvalue)
{
tempos.x=x;
tempos.y=min(y+1,m);
image[tempos.x][tempos.y]=newColor;
qpos.push(tempos);
}
}
return image;
}
};
执行结果:
通过
显示详情
添加备注
执行用时:4 ms, 在所有 C++ 提交中击败了96.89%的用户
内存消耗:13.7 MB, 在所有 C++ 提交中击败了51.02%的用户
通过测试用例:277 / 277
题目竟然是简单难度,我还是太菜了。
深度搜索的办法是这样的,先抄过来,以后就会了。
class Solution {
public:
const int dx[4] = {1,0,0,-1};
const int dy[4] = {0,1,-1,0};
//深度优先搜索
void dfs(vector<vector<int>>& image, int x, int y, int color, int newColor){
if(image[x][y] == color){
image[x][y] = newColor;
for(int i = 0; i < 4; i++){
int mx = x + dx[i];
int my = y + dy[i];
if(mx >= 0 && mx < image.size() && my >= 0 && my < image[0].size() && image[mx][my] == color){
dfs(image, mx, my, color, newColor);
}
}
}
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int color = image[sr][sc];
if(color == newColor) return image;
dfs(image, sr,sc, color,newColor);
return image;
}
};