class Solution {
public int closedIsland(int[][] grid) {
int row=grid.length;
int col=grid[0].length;
int sum=0;
for(int i=0;i<col;i++){
// dfs(grid,0,i);
// dfs(grid,row-1,i);
if(grid[0][i]==0){
dfs(grid,0,i);
}
if(grid[row-1][i]==0){
dfs(grid,row-1,i);
}
}
for(int i=0;i<row;i++){
// dfs(grid,i,0);
// dfs(grid,i,col-1);
if(grid[i][0]==0){
dfs(grid,i,0);
}
if(grid[i][col-1]==0){
dfs(grid,i,col-1);
}
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]==0){
dfs(grid,i,j);
sum++;
}
}
}
return sum;
}
public void dfs(int[][] grid,int i,int j){
int row=grid.length;
int col=grid[0].length;
if(i<0||j<0||i>=row||j>=col||grid[i][j]==1){
return ;
}
grid[i][j]=1;
dfs(grid,i+1,j);
dfs(grid,i-1,j);
dfs(grid,i,j+1);
dfs(grid,i,j-1);
return;
}
}
统计封闭岛屿的数目 1254
最新推荐文章于 2024-11-02 09:55:19 发布