733. 图像渲染 - 力扣(LeetCode) (leetcode-cn.com)
大佬这句话写的好好,引用一下!广度和深度的核心思想:
广度:先把当前结点完全扩展开。深度:先跳到下一个结点
广度优先算法就是给多个方向,向四周发散。
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
int color=image[sr][sc];
if(color==newColor)return image;
image[sr][sc]=newColor;
queue<pair<int, int>> q;
q.emplace(sr,sc);
while(!q.empty()){
int x = q.front().first;
int y=q.front().second;
q.pop();
for (int i=0;i<4;i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (0 <= ny && ny < image[0].size() && 0 <= nx && nx < image.size() && image[nx][ny] == color)
{
image[nx][ny] = newColor;
q.emplace(nx, ny);
}
}
}
return image;
}
深度优先算法 套模板写的
class Solution {
public:
int color;
void dfs(vector<vector<int>>& image, int sr, int sc, int newColor)
{
if(sr < 0 || sc < 0 || sr > image.size() - 1 || sc > image[0].size() - 1 || image[sr][sc] != color){
return;
}
image[sr][sc] = newColor;
dfs(image, sr + 1, sc, newColor);
dfs(image, sr, sc + 1, newColor);
dfs(image, sr - 1, sc, newColor);
dfs(image, sr, sc - 1, newColor);
return;
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
color=image[sr][sc];
if(newColor==color)return image;
dfs(image,sr,sc,newColor);
return image;
}
};
695. 岛屿的最大面积 - 力扣(LeetCode) (leetcode-cn.com)
套用dfs模板
class Solution {
public:
int dfs(vector<vector<int>>& grid,int i,int j){
if (i<0||j<0||i>=grid.size()||j>=grid[0].size()||grid[i][j]==0) {
return 0;}//救命这里一定要先判断边界条件
int n=1;
grid[i][j]=0;
n+=dfs(grid,i,j+1);
n+=dfs(grid,i+1,j);
n+=dfs(grid,i,j-1);
n+=dfs(grid,i-1,j);
return n;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int maxx=0;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]==1)
{
maxx=max(maxx,dfs(grid,i,j));
}
}
}
return maxx;
}
};