https://leetcode-cn.com/problems/ZL6zAn/
解题思路:
- 采用BFS:需要用到额外空间队列或者栈
采用DFS:不需要额外空间- 注意:
grid的更新
//DFS
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int ans = 0;
for(int i = 0; i < grid.size(); i ++){
for(int j = 0; j < grid[0].size(); j ++){
// 如果可以进入
if(grid[i][j]==1){
ans = max(ans, dfs(i, j ,grid));
}
}
}
return ans;
}
int dfs(int x, int y, vector<vector<int>>& grid) {
// 不符合条件判断
if(x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || grid[x][y] == 0)
return 0;
// 符合条件要置零(设置为不可走的标记),防止重复计算
grid[x][y] = 0;
// 递归调用
return 1 + dfs(x - 1, y, grid) + dfs(x, y + 1, grid) + dfs(x + 1, y, grid) + dfs(x, y - 1, grid);
}
};
//BFS
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
vector<vector<int> > dis = {{-1,0},{1,0},{0,1},{0,-1}};
vector<vector<bool> >vistited(grid.size(),vector<bool>(grid[0].size(),false));
int res = 0;
for(int i = 0;i<grid.size();++i){
for(int j = 0;j<grid[0].size();++j){
if(grid[i][j]==1 && !vistited[i][j]){
int temparea = BFS(grid,vistited,dis,i,j);
res = max(res,temparea);
}
}
}
return res;
}
int BFS(const vector<vector<int> > grid,vector<vector<bool> >& vistited,const vector<vector<int> >& dis,int r,int c){
vistited[r][c]=true;
queue<pair<int,int> >mqueue;
mqueue.push({r,c});
int area = 0;
while(!mqueue.empty()){
auto pos = mqueue.front();
mqueue.pop();
area++;
for(auto d : dis){
int x = pos.first + d[0];
int y = pos.second + d[1];
if(x>=0 && x<grid.size() && y>=0 && y<grid[0].size() && !vistited[x][y] && grid[x][y]==1){
mqueue.push({x,y});
vistited[x][y] = true;
}
}
}
return area;
}
};