Very simple Java solution with explanation


  • 0
    B
    public class Solution {
        //add up all the sides of land cells that are touching water
        public int islandPerimeter(int[][] grid) {
            int perimeter = 0;
            //loop over grid
            for(int i=0; i<grid.length;i++){
                for(int j=0;j<grid[0].length;j++){
                    //if it is land
                    if(grid[i][j]>0){
                        //water above
                        if(i-1<0 || grid[i-1][j]==0){
                            perimeter++;
                        }
                        //water below
                        if(i+1>=grid.length || grid[i+1][j]==0){
                            perimeter++;
                        }
                        //water to the left
                        if(j-1<0 || grid[i][j-1]==0){
                            perimeter++;
                        }
                        //water to the right
                        if(j+1>=grid[0].length || grid[i][j+1]==0){
                            perimeter++;
                        }
                    }
                }
            }
            return perimeter;
        }
    }

Log in to reply
 

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