Calculating Perimeter just by looking at neighbours adjacent to a land


  • 0
    N

    Re: clear and easy java solution'

    public int islandPerimeter(int[][] grid) {
        int perimeter = 0;
       for(int i=0;i<grid.length;i++) {
           for(int j=0;j<grid[i].length;j++) {
               int eachLandPermiterToConsider = 0;
               if(grid[i][j] == 1) {
                   if(i==0) eachLandPermiterToConsider++;
                   if(j==0) eachLandPermiterToConsider++;
                   if(j==grid[i].length-1) eachLandPermiterToConsider++;
                   if(i==grid.length-1) eachLandPermiterToConsider++;
                   if(i>=0 && i+1< grid.length && (grid[i+1][j] == 0)) eachLandPermiterToConsider ++;
                   if(i>0 && i< grid.length && (grid[i-1][j] == 0)) eachLandPermiterToConsider ++;
                   if(j>0 && j< grid[i].length && (grid[i][j-1] == 0)) eachLandPermiterToConsider ++;
                   if(j>=0 && j+1< grid[i].length && (grid[i][j+1] == 0)) eachLandPermiterToConsider ++;
               }
               perimeter = perimeter + eachLandPermiterToConsider;
           }
       }
        return perimeter;
    }

Log in to reply
 

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