Fast, clear Java solution


  • 0
    X

    The idea of my algorithm is to determine the type land piece. Each type of land piece could add 4 or 2 or 0 to the perimeter.

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int p=0;
            int[] addition = {4,2,0};
            for(int i=0; i<grid.length; i++){
                for(int j=0; j<grid[0].length; j++){
                    if(grid[i][j]==1){
                        int t=0;
                        if(i>0 && grid[i-1][j]==1)  t++;
                        if(j>0 && grid[i][j-1]==1)  t++; 
                        p += addition[t];
                    }
                }
            }
            return p;
        }
    }
    

Log in to reply
 

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