Easy to understand Java Solution


  • 0
    A
    public int numIslands(char[][] grid) {
            int rows = grid.length;
            if(rows == 0) return 0;
            int cols = grid[0].length;
            int count = 0;
            for(int i = 0; i < rows; i++){
                for(int j=0; j < cols; j++){
                    if(grid[i][j] == '1'){
                        count++;
                        updateGrid(i, j, rows, cols, grid);
                    }
                }
            }
            return count;
    }
    
    private void updateGrid(int x, int y, int rows, int cols, char[][] grid){
            if(x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] == '1'){
                grid[x][y] = '0';
                updateGrid(x+1, y, rows, cols, grid);
                updateGrid(x-1, y, rows, cols, grid);
                updateGrid(x, y+1, rows, cols, grid);
                updateGrid(x, y-1, rows, cols, grid);
            }
    }
    

Log in to reply
 

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