short and simple Java solution

  • 0

    To compute the perimeter of the island, we firstly determine the contribution of each "1" block to the perimeter. Since there are no lakes in the island, for each "1" block, we try to find the number of its adjacent "0" blocks and the map boundaries this "1" block has. Finally, we add all those numbers up to get the perimeter value. The following is the Java code:

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int rl=grid.length, cl=grid[0].length;
            int res=0;
            for(int i=0;i<rl;i++){
                for(int j=0;j<cl;j++){
                        if(i-1<0||grid[i-1][j]==0) res++;
                        if(i+1>rl-1||grid[i+1][j]==0) res++;
                        if(j-1<0||grid[i][j-1]==0) res++;
                        if(j+1>cl-1||grid[i][j+1]==0) res++;
            return res;

Log in to reply

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