Skip to main content

Island Area and Water Boundary

medium
Software engineer

(This question is a variation of the LeetCode question 200. Number of Islands. If you haven't completed that question yet, it is recommended to solve it first.)

You are given a 2D binary grid of size m x n, where each cell is either 0 (water) or 1 (land). An island is defined as a group of connected land cells (1s) where connection is only possible through vertical or horizontal neighbors.

For each island in the grid, compute:

  1. The area: the total number of land cells in the island.
  2. The water boundary count: the number of distinct water cells horizontally or vertically adjacent to the island. A water cell is counted at most once for each island, even if it touches multiple sides of the island. Do not count grid boundaries as water cells.

Return a list of pairs, where each pair contains the area and the water boundary count for an island. The order of the pairs in the output list does not matter.

Example 1

Input

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

Output

[[3, 5]]

Explanation

The single island consists of three land cells at (0, 1), (1, 0), and (1, 1), giving an area of 3. The distinct water cells adjacent to it are located at (0, 0), (0, 2), (1, 2), (2, 0), and (2, 1). This results in a water boundary count of 5. Grid boundaries are not included.

Example 2

Input

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

Output

[[1, 2], [1, 2], [1, 2], [1, 2]]

Explanation

There are 4 separate islands in the corners, each with an area of 1 and bounded by 2 adjacent water cells.

Example 3

Input

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

Output

[[3, 3], [3, 6], [2, 4]]

Constraints

  • 1 <= m, n <= 100
  • grid[i][j] is either 0 or 1.

Screening

ArrayBreadth-First SearchDepth-First SearchGraph TheoryHash TableMatrix
Language
Code editor loads in the browser.

Output

Input

[[0,1,0],[1,1,0],[0,0,0]]

Expected

[[3,5]]

Your output

Run to see your output.