Java, DFS + boolean[][] to judge


  • 0
    J
    public class Solution {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0) {
          return 0;
        }
        int count = 0;
        boolean[][] isUsed = new boolean[grid.length][grid[0].length];
        for(int i = 0; i < grid.length; i++) {
          for(int j = 0; j < grid[0].length; j++) {
            if(grid[i][j] == '1' && isUsed[i][j] == false) {
              count++;
              floodFill(grid, isUsed, i, j);
            }
          }
        }
        return count;
    }
    
    private void floodFill(char[][] grid, boolean[][] isUsed, int i, int j) {
      if(i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == '1'&& isUsed[i][j] == false) {
        isUsed[i][j] = true;
        floodFill(grid, isUsed, i - 1, j);
        floodFill(grid, isUsed, i, j - 1);
        floodFill(grid, isUsed, i + 1, j);
        floodFill(grid, isUsed, i, j + 1);
      }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.