Island Area and Water Boundary
Problem statement
You are given a non-empty rectangular binary matrix grid. A cell containing 1 is land and a cell containing 0 is water. An island is a maximal group of land cells connected horizontally or vertically.
For every island, compute a pair [area, waterBoundary]:
areais the number of land cells in the island.waterBoundaryis the number of distinct in-grid water cells horizontally or vertically adjacent to at least one cell in that island. Count a water cell at most once for the same island, even when it touches multiple island cells. Do not count positions outside the matrix.
Return the pairs in the order in which their islands are first encountered while scanning grid from top to bottom and left to right.
Function
islandAreaAndWaterBoundary(grid: int[][]) → int[][]Examples
Example 1
grid = [[0,1,0],[1,1,0],[0,0,0]]return = [[3,5]]The three land cells form one island. Its five distinct adjacent water cells are [0,0], [0,2], [1,2], [2,0], and [2,1].
Example 2
grid = [[1,0,1],[0,0,0],[1,0,1]]return = [[1,2],[1,2],[1,2],[1,2]]Each corner land cell is a separate one-cell island with two adjacent water cells.
Example 3
grid = [[1,1,0,0,0],[1,0,0,1,1],[0,0,0,1,0],[0,1,1,0,0]]return = [[3,3],[3,6],[2,4]]The row-major scan discovers islands with areas 3, 3, and 2. Their distinct water-boundary counts are 3, 6, and 4.
Constraints
1 <= grid.length <= 100.1 <= grid[i].length <= 100.- Every row has the same length.
- Every cell is either
0or1.