Java solution


  • -1
    M

    Please suggest if you see anything which is not optimised enough. Thanks!

    public class Solution {
    public int islandPerimeter(int[][] grid) {
    int perimeter = 0;
    int hLength = grid[0].length;
    int vLength = grid.length;
    for(int i=0; i<vLength; i++){
    for(int j=0; j<hLength; j++){
    if(grid[i][j] == 0) continue;
    if(i==0) perimeter++;
    if(j==0) perimeter++;
    if(i==vLength-1) perimeter++;
    if(j==hLength-1) perimeter++;
    if(i>0 && grid[i-1][j] != 1) perimeter++;
    if(j>0 && grid[i][j-1] != 1) perimeter++;
    if(i<vLength-1 && grid[i+1][j] != 1) perimeter++;
    if(j<hLength-1 && grid[i][j+1] != 1) perimeter++;
    }
    }

        return perimeter;
    }
    

    }


Log in to reply
 

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