Simple Java Solution (beats 75%)


  • 0
    V
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int count = 0;
            int diff = 0;
            for(int i = 0; i<grid.length; i++){
                for(int j = 0; j<grid[0].length; j++){
                    if(grid[i][j] == 1){
                        count++;
                        int up = i - 1 < 0 ? 0 : grid[i-1][j];
                        int down = i + 1 > grid.length -1 ? 0 : grid[i+1][j];
                        int left = j - 1 < 0 ? 0 : grid[i][j-1];
                        int right = j + 1 > grid[0].length -1 ? 0 : grid[i][j+1];
                        diff = diff+ up+down+left+right;
                    }
                }
            }
            return count*4 - diff;
        }
    }

Log in to reply
 

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