class Solution {
public void dfs(char[][] grid,int r, int c){
int rn = grid.length;
int cn = grid[0].length;
if(r < 0 || c < 0 ||r >= rn || c >= cn || grid[r][c] == '0'){
return;
}
grid[r][c] = '0';
dfs(grid,r - 1,c);
dfs(grid,r + 1,c);
dfs(grid,r,c - 1);
dfs(grid,r,c + 1);
}
public int numIslands(char[][] grid) {
int rn = grid.length;
int cn = grid[0].length;
int nums_islands = 0;
for(int i = 0;i < rn;i++){
for (int j = 0; j < cn;j++){
if(grid[i][j] == '1'){
nums_islands++;
dfs(grid,i,j);
}
}
}
return nums_islands;
}
}
200. 岛屿数量(深度优先遍历)
最新推荐文章于 2024-11-06 20:43:37 发布