Loop with checking 4 side / T : O(N), S : O(1)


  • 0
    J
    public int islandPerimeter(int[][] grid) {
            int peri = 0;
            for(int i = 0; i < grid.length; i++){
               for(int j = 0; j < grid[0].length; j++){
                   if(grid[i][j] == 1){
                       if(i-1 < 0 || grid[i-1][j] == 0)
                           peri++;
                       if(j-1 < 0 || grid[i][j-1] == 0)
                           peri++;
                       if(i+1 >= grid.length || grid[i+1][j] == 0)
                           peri++;
                       if(j+1 >= grid[0].length || grid[i][j+1] == 0)
                           peri++;
                   } 
               }
            }
            return peri;
        }
    

Log in to reply
 

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