public class Solution {
public int numIslands(char[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int islandCount = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == '1') {
islandCount++;
markIsland(grid, r, c, rows, cols);
}
}
}
return islandCount;
}
private void markIsland(char[][] grid, int r, int c, int rows, int cols) {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') {
return;
}
grid[r][c] = '0';
markIsland(grid, r + 1, c, rows, cols);
markIsland(grid, r - 1, c, rows, cols);
markIsland(grid, r, c + 1, rows, cols);
markIsland(grid, r, c - 1, rows, cols);
}
}