463. Island Perimeter
Problem
The grid has exactly one island of 1s (connected up, down, left, right) and no lakes inside it. Return the island's perimeter, with every cell a 1×1 square.
Example: [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] → 16
Every land cell contributes 4 edges; every pair of adjacent land cells hides 2 of them. Count land cells and right/down land neighbours: 4·land − 2·adjacent.
Complexity: O(R·C).
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
land = shared = 0
for r, row in enumerate(grid):
for c, v in enumerate(row):
if v:
land += 1
shared += (r + 1 < len(grid) and grid[r + 1][c]) + (c + 1 < len(row) and row[c + 1])
return 4 * land - 2 * shared
assert Solution().islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]) == 16
assert Solution().islandPerimeter([[1]]) == 4
assert Solution().islandPerimeter([[1, 0]]) == 4
assert Solution().islandPerimeter([[1, 1], [1, 1]]) == 8
class Solution {
public int islandPerimeter(int[][] grid) {
int land = 0, shared = 0;
for (int r = 0; r < grid.length; r++)
for (int c = 0; c < grid[0].length; c++)
if (grid[r][c] == 1) {
land++;
if (r + 1 < grid.length && grid[r + 1][c] == 1) shared++;
if (c + 1 < grid[0].length && grid[r][c + 1] == 1) shared++;
}
return 4 * land - 2 * shared;
}
}
func islandPerimeter(grid [][]int) int {
land, shared := 0, 0
for r, row := range grid {
for c, v := range row {
if v == 1 {
land++
if r+1 < len(grid) && grid[r+1][c] == 1 { // each shared edge hides two sides
shared++
}
if c+1 < len(row) && row[c+1] == 1 {
shared++
}
}
}
}
return 4*land - 2*shared
}