Island Perimeter

Given a grid with exactly one island, return the perimeter of that island. The island is formed by connected 1s in four directions. Pattern focus: Component traversal. Count exposed sides while traversing the island component.

Input Format

grid = 2D binary matrix

Output Format

island perimeter

Constraints

  • 1 <= rows * cols <= 10^5
  • The grid contains exactly one island.

Examples

Example 1:

Input:

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

Output:

16

Explanation:

The island boundary has perimeter 16.

Example 2:

Input:

grid = [[1]]

Output:

4

Explanation:

A single land cell contributes four edges.

Example 3:

Input:

grid = [[1,0]]

Output:

4

Explanation:

One isolated land cell still has perimeter 4.

Loading...
Island Perimeter - Graph Traversal DSA Problem