Design Gurus Logo
Problem Challenge 1 (easy)

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 =

The island is outlined in red. Counting every side where land meets water or the edge of the matrix gives 14.
The island is outlined in red. Counting every side where land meets water or the edge of the matrix gives 14.

Output: 14

Explanation: The boundary of the island constitutes 14 sides.

Example 2

Input: matrix =

A narrower matrix, with the island again outlined in red. The same count gives 12.
A narrower matrix, with the island again outlined in red. The same count gives 12.

Output: 12

Explanation: The boundary of the island constitutes 12 sides.

Example 3

Input: matrix =

The island is a ring around one water cell. The outer wall is 12 sides and the wall around the lake is 4, giving 16.
The island is a ring around one water cell. The outer wall is 12 sides and the wall around the lake is 4, giving 16.

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:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory