题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5f62c6e4f179216ef6247ba842a62527.png)
代码
class Solution {
public int numIslands(char[][] grid) {
int islandNum = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == '1'){
infect(grid, i, j);
islandNum++;
}
}
}
return islandNum;
}
public void infect(char[][] grid, int i, int j){
if(i < 0 || j < 0 ||i >= grid.length
|| j >= grid[0].length || grid[i][j] != '1'){
return;
}
grid[i][j] = '0';
infect(grid, i + 1, j);
infect(grid, i - 1, j);
infect(grid, i, j + 1);
infect(grid, i, j - 1);
}
}
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/44582a3690bcadb567257412152b7708.png)