SDE & MLE Prep

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