A 1-cell has four sides and it can contribute at most 4 to the perimeter. If a side is shared with another 1-cell, that side does not contribute to perimeter. So, for each 1 cell in the grid, we count how many of its four sides are shared and then add (4 – shared_count) to perimeter.
Time: , space:
.
from itertools import product as cartesian
class Solution:
def count_shared_sides(self, r, c, grid, m, n) -> int:
deltas = [(-1, 0), (0, 1), (1, 0), (0, -1)]
shared_count = 0
for dr, dc in deltas:
r2, c2 = r + dr, c + dc
if (0 <= r2 < m) and (0 <= c2 < n) and grid[r2][c2] == 1:
shared_count += 1
return shared_count
def islandPerimeter(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
side_count = 4
perimeter = 0
for r, c in cartesian(range(m), range(n)):
if grid[r][c] == 0:
continue
perimeter += side_count - self.count_shared_sides(r, c, grid, m, n)
return perimeter
Leave a comment