Medium
不知道做过多少回了,有时还是会出一些小bug.
详细讲解:https://www.youtube.com/watch?v=XSmgFKe-XYU
public class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0){
return 0;
}
int count = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (grid[i][j] == '1'){
dfsSearch(i, j, grid);
count++;
}
}
}
return count;
}
private void dfsSearch(int i, int j, char[][] grid){
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1'){
return;
}
grid[i][j] = '0';
dfsSearch(i + 1, j, grid);
dfsSearch(i - 1, j, grid);
dfsSearch(i, j + 1, grid);
dfsSearch(i, j - 1, grid);
}
}