JAVA - Simple with scan all the spot once


  • 0
    N
    public class Solution {
        public int islandPerimeter(int[][] grid) {
            int sumOfIsland = 0;
            int sumOfConnect = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (grid[i][j] == 1) {
                        sumOfIsland++;
                        int rightSpot = j+1;
                        int downSpot = i+1;
                        if(rightSpot< grid[i].length && grid[i][rightSpot] == 1) sumOfConnect ++;
                        if(downSpot< grid.length && grid[downSpot][j] == 1) sumOfConnect ++;
                    }
                }
            }
            return sumOfIsland * 4 - sumOfConnect * 2;
        }
    }
    

Log in to reply
 

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