Problems/463. Island Perimeter

463. Island Perimeter

EasyMatrixGraphDFSMath

You are given a 2D binary grid containing 1s (representing land) and 0s (representing water). Find and return the perimeter of the island.

The grid contains exactly one island (i.e., one or more connected land cells). The island does not have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. Grid cells are connected horizontally and vertically (not diagonally).

Example 1
Input: grid = [ [0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0] ]
Output: 16
The borders of the island add up to a perimeter of 16.
Example 2
Input: grid = [ [1, 1], [1, 1] ]
Output: 8
A 2x2 island has 4 outer borders of length 2 each, giving a perimeter of 8.
Example 3
Input: grid = [ [1] ]
Output: 4
A single land cell has 4 boundaries, so the perimeter is 4.
Visualizer

Visualizer will appear here