131 ms solution; easy to understand


  • 0
    S
    public class Solution {
        public static int islandPerimeter(int[][] grid) {
            int totPeri = 0, cellPeri = 0;
            for (int i=0; i<grid.length; i++){
                for (int j=0; j<grid[0].length; j++){
                    if (grid[i][j] != 1){            //consider only land positions
                        continue;
                    }
                    cellPeri = 4;                    //default perimeter for each cell
                    if (j-1 >= 0 && grid[i][j-1] == 1){ 
                        cellPeri--;                  //if a neighbour is found, reduce the perimeter
                    }
                    if (j+1 < grid[0].length && grid[i][j+1] == 1){
                        cellPeri--;
                    }
                    if (i-1 >=0 && grid[i-1][j] == 1){
                        cellPeri--;
                    }
                    if (i+1 < grid.length && grid[i+1][j] == 1){
                        cellPeri--;
                    }
                    totPeri = totPeri + cellPeri;
                }
            }
            return totPeri;
        }
    }
    

Log in to reply
 

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