给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
示例 :
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
方法:深度优先搜索
class Solution {
public int numIslands(char[][] grid) {
int h = grid.length;
int l = grid[0].length;
if(h==0 || grid==null){
return 0;
}
int res = 0;
for(int i=0;i<h;i++){
for(int j=0;j<l;j++){
//如果当前节点为1,则启动深度优先搜索,并开始计数
if(grid[i][j] == '1'){
res += 1;
dfs(grid, i, j);
}
}
}
return res;
}
void dfs(char[][] grid, int i, int j){
int h = grid.length;
int l = grid[0].length;
//跳出搜索的条件:越界或当前的节点是0
if(i<0 || j<0 || i>=h || j>=l || grid[i][j]=='0'){
return ;
}
//进入到深度优先搜索后,表明grid[i][j]=‘1’且已经被计数了,所以需要置为0,后面不需要再统计这个节点
grid[i][j] = '0';
dfs(grid,i-1,j);
dfs(grid,i+1,j);
dfs(grid,i,j-1);
dfs(grid,i,j+1);
}
}