Java Island count and remove solution (very fast)


  • 1
    D
    public int numIslands(char[][] grid) {
        if(grid == null) return 0;
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '0') continue;
                count++;
                clearIsland(grid, grid.length, grid[0].length,  i, j);
            }
        }
        return count;
    }
    
    private void clearIsland(char[][] grid, int row, int column, int i, int j) {
        if(i < 0 || j < 0 || i == row || j == column || grid[i][j] == '0') return;
        grid[i][j] = '0';
        clearIsland(grid, row, column, i, j + 1);
        clearIsland(grid, row, column, i + 1, j);
        clearIsland(grid, row, column, i - 1, j);
        clearIsland(grid, row, column, i, j - 1);
    }

Log in to reply
 

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