200. Number of Islands#

 1public int numIslands(char[][] grid) {
 2  int count = 0;
 3
 4  for (int i = 0; i < grid.length; i++) {
 5    for (int j = 0; j < grid[0].length; j++) {
 6      if (grid[i][j] == '1') {
 7        count++;
 8        dfs(grid, i, j);
 9      }
10    }
11  }
12
13  return count;
14}
15
16private void dfs(char[][] grid, int i, int j) {
17  if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
18    return;
19  }
20
21  if (grid[i][j] != '1') {
22    return;
23  }
24
25  grid[i][j] = '0';
26
27  dfs(grid, i - 1, j); // top
28  dfs(grid, i, j - 1); // left
29  dfs(grid, i + 1, j); // bottom
30  dfs(grid, i, j + 1); // rigth
31}