代码随想录Day67 | 695.岛屿的最大面积 1020.飞地的数量
695.岛屿的最大面积
文档讲解:代码随想录
视频讲解:
状态
采用bfs,这道题相较于之前的题变为了求岛屿的最大面积。那就说明我们每遇到一个新的岛屿就要重新计算一个面积,然后和之前的最大面积比较。
class Solution {
private:
int dir[4][2] = {0,1,1,0,-1,0,0,-1};
int count;
public:
void bfs(vector<vector<int>>& grid, vector<vector<bool>>& vistied, int x,int y)
{
queue<pair<int,int>> check;
check.push({x,y});
visitied[x][y] = true;
while(!check.empty())
{
pair<int,int> cur = check.front();
check.pop();
int curx = cur.first;
int cury = cur.second;
for(int i=0;i<4;i++)
{
int nextx = curx+dir[i][0];
int nexty = cury+dir[i][1];
//如果超过范围那么跳过
if(nextx < 0 || nextx >= grid.size() || nexty <0 || nexty>=grid[0].size()) continue;
//没有被访问过,且为1
if(!visited[nextx][nexty] && grid[nextx][nexty] == 1)
{
visited[nextx][nexty] = true;
//面积+1
count++;
check.push({nextx,nexty});
}
}
}
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
vector<vector<bool>> visited(n,vector<bool>(m,false));
int res = 0;
for(int i = 0;i<n;i++)
{
for(int j = 0;j<m;j++)
{
//第一次bfs
//当遇到没有被访问过,且为1说明是一块新的陆地
if(!visited[i][j] && grid[i][j] == 1)
{
//重置count;
count = 1;
bfs(grid,visited,i,j);
res = max(count,res);
}
}
}
return res;
}
};
1020.飞地的数量
文档讲解:代码随想录
视频讲解:
状态
将边缘陆地形成的岛屿全部变为海洋后,再重新遍历整个图,得到的就是飞地。
class Solution {
private:
int dir[4][2] = {0,1,1,0,-1,0,0,-1};
int res = 0;
public:
void bfs(vector<vector<int>>& grid,int x,int y)
{
queue<pair<int,int>> check;
check.push({x,y});
grid[x][y] = 0;
res++;
while(!check.empty())
{
pair<int,int> cur = check.front();
check.pop();
int curx = cur.first;
int cury = cur.second;
for(int i = 0;i<4;i++)
{
int nextx = curx+dir[i][0];
int nexty = cury+dir[i][1];
if(nextx <0 || nextx>=grid.size() || nexty<0 || nexty>=grid[0].size())
{
continue;
}
if(grid[nextx][nexty] == 1)
{
res++;
check.push({nextx,nexty});
grid[nextx][nexty] = 0;
}
}
}
}
public:
int numEnclaves(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
//从左岸和右岸向中间淹没
for(int i = 0;i<n;i++)
{
if(grid[i][0] == 1) bfs(grid,i,0);
if(grid[i][m-1] == 1) bfs(grid,i,m-1);
}
//从上面和下面向中间淹没
for(int j = 0;j<m;j++)
{
if(grid[0][j] == 1) bfs(grid,0,j);
if(grid[n-1][j] == 1) bfs(grid,n-1,j);
}
res = 0;
//统计剩余单元岛屿个数
for(int i = 0;i<n;i++)
{
for(int j= 0;j<m;j++)
{
if(grid[i][j] == 1)
{
bfs(grid,i,j);
}
}
}
return res;
}
};