Given a 2D grid of land and water, compute the total perimeter of the island formed by the land cells.
You are given a 2D grid where each cell is either land (1) or water (0). The grid contains exactly one island: a group of horizontally or vertically adjacent land cells.
Your task is to compute the perimeter of the island.
A land cell contributes to the perimeter for each of its four sides that touches water or the boundary of the grid.
Return the total perimeter of the island.
grid with m rows and n columns.grid[i][j] = 1 means land, and grid[i][j] = 0 means water.1 <= m, n0 or 1.Example 1
Input
grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output
16
Explanation
Each land cell contributes sides that touch water or the boundary. Summing all exposed sides gives a perimeter of 16.
Example 2
Input
grid = [[1]]
Output
4
Explanation
A single land cell has four sides, all touching the boundary.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.