Skip to content

Perimeter Of An Island

Easy#grid-scan#neighbour-check~20 min

The mission

Problem

A grid holds 1 for land and 0 for water, and all the land forms a single connected island with no lakes inside it. Measure the length of the island's coastline, counting one unit for each cell side that touches water or the edge of the grid.

Examples

Input:  grid = [[0, 1, 0, 0],
                [1, 1, 1, 0],
                [0, 1, 0, 0],
                [1, 1, 0, 0]]
Output: 16
Input:  grid = [[1, 1],
                [1, 1]]
Output: 8
Why:    a solid square of four cells has eight exposed sides
Input:  grid = [[1]]
Output: 4
Why:    edge case, a lone cell is exposed on every side

Hints

0 / 3

Target time
O(rows · cols)
Target space
O(1)

Constraints

  • cells are 1 (land) or 0 (water)
  • the land forms one connected island with no lakes

Stuck on the idea rather than the code? Grid Traversal covers it.

Python 3Ctrl+Enter runs