```
public int numIslands(char[][] grid) {
if (grid.length == 0)
return 0;
int num = 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'){
num += 1;
cancelIsland(grid, i, j);
}
}
}
return num;
}
public void cancelIsland(char[][] grid, int i, int j){
int m = grid.length;
int n = grid[0].length;
grid[i][j] = '0';
if(j+1 < n && grid[i][j+1] == '1')
cancelIsland(grid, i, j+1);
if(i+1 < m && grid[i+1][j] == '1')
cancelIsland(grid, i+1, j);
if(j-1 >= 0 && grid[i][j-1] == '1')
cancelIsland(grid, i, j-1);
if(i-1 >= 0 && grid[i-1][j] == '1')
cancelIsland(grid, i-1, j);
return;
}
```