
Problem Statement
You are given a 2D matrix (a grid) where every cell holds either 1 for land or 0 for water. Cells connect horizontally and vertically, never diagonally.
An island is a group of connected land cells, and the water around it reaches the edge of the matrix. Every cell is a square with sides of length 1.
The island may contain a lake, which is water fully enclosed by land. The wall around a lake is part of the island's boundary, so it counts toward the perimeter exactly as the outer edge does.
The matrix holds at most one island. Write a function that returns its perimeter, which is the number of cell sides where land meets water or the edge of the matrix. If the matrix holds no land at all, the perimeter is 0.
Example 1
Input: matrix =
Output: 14
Explanation: The boundary of the island constitutes 14 sides.
Example 2
Input: matrix =
Output: 12
Explanation: The boundary of the island constitutes 12 sides.
Example 3
Input: matrix =
Output: 16
Explanation: The island is a ring of land around one water cell. The outer wall is 12 sides and the wall around the lake is 4 sides, giving 16.
Try it yourself
Try solving this question here:
.....
.....
.....