dsa · easy

Island Perimeter

grid is a rectangular map. 1 is land, 0 is water. Land cells connect along edges (not diagonals). There is exactly one island: one connected group of land, with no lakes (no water completely enclosed by land). Return the island's perimeter: each land edge that touches water or the border of the map contributes 1.

Example

grid = [[1, 1], [1, 0]]:

`` 1 1 1 0 ``

Three land cells. The top-left land has two outer edges (top, left). The top-right land has three (top, right, bottom). The bottom-left land has three (left, bottom, right). Total 2 + 3 + 3 = 8.

grid = [[1]] is a single cell, so four outer edges → 4.

grid = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] is a plus shape. Each of the four arms exposes 3 edges and the center exposes none → 12.

## Arguments - grid — rectangular 0/1 map; 1 is land, 0 is water

Constraints

1 <= grid.length, grid[i].length <= 100 grid[i][j] is 0 or 1 There is exactly one island (one or more connected land cells) The island has no lakes Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[[1,1],[1,0]]

Expected:
8

Example 2

Input:
[[1]]

Expected:
4

Example 3

Input:
[[0,1,0],[1,1,1],[0,1,0]]

Expected:
12

Open in the Dojo editor