也是一道很老很老的题了。
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
class Solution {
public int numIslands(char[][] grid) {
int count = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == '1'){
count++;
helper(grid, i, j);
}
}
}
return count;
}
public void helper(char[][] grid, int i, int j){
if(i >= 0 && i < grid.length && j >= 0 && j < grid[0].length){
if(grid[i][j] =='0' || grid[i][j] == '*')
return;
grid[i][j] = '*';
helper(grid, i, j + 1);
helper(grid, i, j - 1);
helper(grid, i + 1, j);
helper(grid, i - 1, j);
}
}
}