A survey map is a grid of 1 (land) and 0 (water), each cell 1 km square. Everything outside the grid is sea.
Implement coastline(grid: list[list[int]]) -> int: the total shoreline in km, meaning every side of a land cell that faces water or the map's edge. Lake shores count too.
coastline([
[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
])
# 16
coastline([[1, 1],
[1, 1]]) # 8
coastline([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]]) # 16 (12 outside, 4 around the lake)
coastline([[0, 0]]) # 0
Up to 500 × 500 cells.
⭐ Bonus: a speed test on 500 × 500 maps earns a star in O(rows·cols).
Show hint
Look at each land cell on its own: which of its four sides are shoreline?