Java solution


  • 0
    W

    Idea: Based on how many neighbors an island has.

    For example, if a island is surrounded by neighbors in both up, down, left right, then this will not have any coastline, so it contributes 0 to the final perimeter.

    Same if it only has up neighbor, it will contribute 3 to the final perimeter.

        public int islandPerimeter(int[][] grid) {
            int res = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (grid[i][j] == 1) {
                        int neighbors = (i == 0 ? 0 : grid[i - 1][j]) +
                                        (j == 0 ? 0 : grid[i][j - 1]) +
                                        (i == grid.length - 1 ? 0 : grid[i + 1][j]) +
                                        (j == grid[i].length - 1 ? 0 : grid[i][j + 1]);
                        res += 4 - neighbors;
                    }
    
                }
            }
            return res;
        }
    
    

Log in to reply
 

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