Loading problem...
You are given a two-dimensional grid of size rows × cols that represents a terrain map. Each cell in the grid contains either a 1 (representing land) or a 0 (representing water).
The grid cells are connected horizontally and vertically (not diagonally). The entire grid is surrounded by water on all sides. There is exactly one contiguous landmass in the grid, formed by one or more adjacent land cells connected horizontally or vertically.
The landmass has no internal water bodies, meaning there are no pockets of water that are completely enclosed within the land. Each cell is a unit square with side length 1.
Your task is to calculate and return the total boundary length (perimeter) of the landmass. The boundary is measured along the edges of land cells that are either adjacent to water cells or touch the edge of the grid.
grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]16The landmass consists of 7 connected land cells. Counting all edges that either touch water or the grid boundary, we get a total perimeter of 16 units.
grid = [[1]]4A single land cell has all 4 edges exposed, giving a perimeter of 4.
grid = [[1,0]]4A single land cell with water on one side and grid boundary on other sides still has a perimeter of 4, as all edges are exposed.
Constraints