Skip to content
BytePatterns

Perimeter Of An Island

EasyMatrix & Grid#grid-scan#neighbour-check~20m

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

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