链接
https://leetcode-cn.com/problems/flood-fill/
耗时
解题:37 min
题解:5 min
题意
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
思路
我以为要返回一个新图,重新上色直接在原图上搞不就行了,但是都已经过了,就懒得改了,记录一下这种返回一个新图的做法。
BFS 判断上下左右的点是否与当前点相同,相同即入队并修改。若新的颜色值和原颜色值相同,则不入队初始坐标。
时间复杂度:
O
(
n
∗
m
)
O(n*m)
O(n∗m) n 图像的高,m 图像的宽
AC代码
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int n = image.size();
int m = image[0].size();
vector<vector<int>> ans(n, vector<int>(m, -1));
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
queue<pair<int, int>> q;
int nowColor = image[sr][sc];
if(nowColor != newColor) {
q.emplace(sr, sc);
}
ans[sr][sc] = newColor;
while(!q.empty()) {
pair<int, int> now = q.front();
q.pop();
for(int i = 0; i < 4; ++i) {
int x = now.first + dir[i][0];
int y = now.second + dir[i][1];
if((x >= 0 && x < n) && (y >= 0 && y < m)) {
if(ans[x][y] == -1 && image[x][y] == nowColor) {
q.emplace(x, y);
ans[x][y] = newColor;
}
}
}
}
for(int i = 0 ; i < n; ++i) {
for(int j = 0; j < m; ++j) {
if(ans[i][j] == -1) {
ans[i][j] = image[i][j];
}
}
}
return ans;
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)