【LeetCode1020】飞地的数量
【摘要】
一、题目
提示:
1 <= A.length <= 5001 <= A[i].length <= 5000 <= A[i][j] <= 1所有行的大小都相同
二...
一、题目
提示:
- 1 <= A.length <= 500
- 1 <= A[i].length <= 500
- 0 <= A[i][j] <= 1
- 所有行的大小都相同
二、思路
从4条边界进行遍历,即遇到边界上的1就递归遍历,把边界上的都为1的连通分量改成数字2,dfs搞完后,就遍历一遍二维数组,剩下的1即所求的飞地数量。
方法和 【LeetCode130】被围绕的区域(dfs)基本一致。
三、C++代码
class Solution {
private:
vector<pair<int,int>>directions{{0,1},{0,-1},{1,0},{-1,0}};
public:
int numEnclaves(vector<vector<int>>& grid) {
int res = 0;
int row=grid.size();//row行数
int col=grid[0].size();//column列数
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]==1 && (i == row-1 || j == col-1
|| i == 0 || j == 0)){
dfs(grid,i,j);
}
}
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j] == 1){
res++;
}
}
}
return res;
}
void dfs(vector<vector<int>>&board,int x,int y){
if(!isarea(board,x,y)){
return;//如果坐标(x,y)超过网格范围,则直接返回
}
if(board[x][y]!=1){
return;//如果不是岛屿(1)则直接返回
}
board[x][y]=2;//将格子标记为已遍历过,重新淹水
for(auto dir:directions){
int newx=x+dir.first,newy=y+dir.second;
if(isarea(board,newx,newy)){//在网格范围内(正常)
//board[x][y]='X';
dfs(board,newx,newy);
}
}
}
bool isarea(vector<vector<int>>&board,int x,int y){//判断点是否在网格内
if(x>=0 && x<board.size() && 0<=y && y<board[0].size()){
return true;
}else{
return false;
}
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
文章来源: andyguo.blog.csdn.net,作者:山顶夕景,版权归原作者所有,如需转载,请联系作者。
原文链接:andyguo.blog.csdn.net/article/details/122550537
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)