~/problems / Graphs / DFS and connected components

Island Perimeter

easy ~12 min

A survey map is a grid of 1 (land) and 0 (water); each cell is a 1 km by 1 km square. Everything outside the grid is sea.

Implement coastline(grid: list[list[int]]) -> int: the total length, in km, of shoreline, meaning every side of a land cell that faces water or the edge of the map. The map may contain several islands and lakes; a lake's shore counts 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
  • 1 <= rows, cols <= 500.
  • Aim for 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