```
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int m = grid.length, n = grid[0].length;
int cnt = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
++cnt;
dfs(grid, i, j);
}
}
}
return cnt;
}
private static final int[] dx = {-1, 1, 0, 0}, dy = {0, 0, -1, 1};
private void dfs(char[][] grid, int i, int j) {
grid[i][j] = '0';
for (int k = 0; k < dx.length; ++k) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < grid.length && y >= 0 && y < grid[x].length && grid[x][y] == '1') {
dfs(grid, x, y);
}
}
}
```