progress

~/problems / Graphs / DFS and connected components

Island Perimeter

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~12 min

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
A 4 by 4 map whose land forms a cross with an L-shaped tail at the bottom; its 16 shoreline sides are drawn as a thick line.
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?

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc