类似LeetCode第 130 题:被围绕的区域(C++)_zj-CSDN博客
从初始点开始,相连的才进行染色。
dfs:
class Solution {
public:
int color, newcolor, m, n;
void dfs(vector<vector<int>>& image, int sr, int sc){
if(sr < 0 || sr >= m || sc < 0 || sc >= n || image[sr][sc] != color) return;
image[sr][sc] = newcolor;
dfs(image, sr-1, sc);
dfs(image, sr+1, sc);
dfs(image, sr, sc-1);
dfs(image, sr, sc+1);
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(newColor == image[sr][sc]) return image;//不用染色
color = image[sr][sc];
newcolor = newColor;
m = image.size();//行
n = image[0].size();//列
dfs(image, sr, sc);
return image;
}
};
bfs
class Solution {
public:
const int dx[4] = {1,0,0,-1};
const int dy[4] = {0,1,-1,0};
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(newColor == image[sr][sc]) return image;//不用染色
int color = image[sr][sc];
int m = image.size(), n = image[0].size();//行、列
queue<pair<int, int>> q;
q.push({sr, sc});
image[sr][sc] = newColor;
while(!q.empty()){
int x = q.front().first, y = q.front().second;
q.pop();
for(int i = 0; i <4; ++i){//检查上下左右
int mx = x + dx[i], my = y + dy[i];
if(mx >= 0 && mx < m && my >= 0 && my < n && image[mx][my] == color){
q.push({mx, my});
image[mx][my] = newColor;
}
}
}
return image;
}
};