super easy to understand, good format, passed first time


  • 0
    L
    
    public class Solution {
        public int numIslands(char[][] grid) {
            int count = 0;
            for (int i = 0; i < grid.length; i ++){
                for (int j = 0; j < grid[0].length; j ++){
                    if (grid[i][j] == '1') {
                        count ++;
                        cover(grid, i, j);
                    }
                }
            }
            
            return count;
        }
        
        private void cover(char[][] grid, int row, int column){
            if (grid[row][column] == '1'){
                grid[row][column] = 'n';
                if (row > 0){
                    if (grid[row-1][column] == '1'){
                        cover(grid, row - 1, column);
                    }
                }
                if (row < grid.length - 1){
                    if (grid[row+1][column] == '1'){
                        cover(grid, row + 1, column);
                    }
                } 
                if (column > 0){
                    if (grid[row][column-1] == '1'){
                        cover(grid, row, column - 1);
                    }
                }
                if (column < grid[0].length - 1) {
                    if (grid[row][column+1] == '1'){
                        cover(grid, row, column + 1);
                    }
                }
            }
        }
    }
    
    
    

Log in to reply
 

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