Basic Java solution (self-explanatory)


  • 0
    L

    The idea is to iterate over 2-d array and add 1 for either it is an edge, or it has a neighbor 0.

        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++) {
                    //add count to each side that is either 
                    //a boundary or water-facing.
                    if(grid[i][j]==1) {
                        if(i==0) {
                            perimeter += 1;
                        }
                        if(i==grid.length-1) {
                            perimeter += 1;
                        }
                        if(j==0) {
                            perimeter += 1;
                        }
                        if(j==grid[i].length-1) {
                            perimeter += 1;
                        }
                        if(i>0 && grid[i-1][j]==0) {
                            perimeter += 1;
                        }
                        if(i<grid.length-1 && grid[i+1][j]==0) {
                            perimeter += 1;
                        }
                        if(j>0 && grid[i][j-1]==0) {
                            perimeter += 1;
                        }
                        if(j<grid[i].length-1 && grid[i][j+1]==0) {
                            perimeter += 1;
                        }
                    }
                }
            }
            return perimeter;
        }
    

Log in to reply
 

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