Problem 579803 · easy · Phase 05 Advanced Algorithms & Graphs

Total Coastline Length

grids · neighbours · boundary handling

A map is given as a grid of 0 (water) and 1 (land). Cells are unit squares; two land cells belong to the same island when they share a side. The coastline of the map is the total length of every unit edge where a land cell touches either water or the edge of the grid. Return the total coastline length summed over all islands (there may be several).

Examples

Input:  grid = [[0,1,0,0],
                [1,1,1,0],
                [0,1,0,0],
                [1,1,0,0]]
Output: 16
Explanation: 7 land cells x 4 sides = 28, minus 2 for each of the 6 shared sides.

Input:  grid = [[1,0,1]]
Output: 8
Explanation: two separate cells, each with 4 exposed sides.

Constraints

  • 1 <= rows, cols <= 100
  • Target O(rows * cols) time.

Goals

  • Visit the 4 neighbours of a grid cell with bounds checks
  • Count edges rather than cells
Starting Python…