200. 岛屿数量

image.png

  1. class Solution {
  2. private int count;
  3. private int[][] direc = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
  4. public int numIslands(char[][] grid) {
  5. if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
  6. int m = grid.length, n = grid[0].length;
  7. for (int i = 0; i < m; i++) {
  8. for (int j = 0; j < n; j++) {
  9. if (grid[i][j] == '1') {
  10. count++;
  11. fill(grid, i, j);
  12. }
  13. }
  14. }
  15. return count;
  16. }
  17. private void fill(char[][] grid, int x, int y) {
  18. if (x < 0 || y < 0 || x == grid.length || y == grid[0].length) return;
  19. if (grid[x][y] != '1') return;
  20. grid[x][y] = '#';
  21. for (int i = 0; i < 4; i++) {
  22. int nextX = x + direc[i][0];
  23. int nextY = y + direc[i][1];
  24. fill(grid, nextX, nextY);
  25. }
  26. }
  27. }