Design Gurus Logo
Problem Challenge 1 (easy)

Problem Statement

You are given a 2D matrix containing only 1s (land) and 0s (water).

An island is a connected set of 1s (land) and is surrounded by either an edge or 0s (water). Each cell is considered connected to other cells horizontally or vertically (not diagonally).

The island may contain lakes, which are water cells fully enclosed by land. The wall around a lake is part of the island's boundary, so it counts toward the perimeter just as the outer edge does. A cell is a square with a side length of 1.

Put simply, the perimeter is the number of cell sides where land meets water or the edge of the matrix. Example 3 below is a ring of land around a single water cell: its outer wall is 12 and its inner wall is 4, giving 16.

The given matrix has only one island, write a function to find the perimeter of that island.

Example 1

Input: matrix =

Image

Output: 14

Explanation: The boundary of the island constitutes 14 sides.

Example 2

Input: matrix =

Image

Output: 12

Explanation: The boundary of the island constitute 12 sides.

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