Island Perimeter

Easy · Matrix · Array · Matrix · Depth-First Search · Breadth-First Search

Problem

You are given a rows x cols grid where grid[i][j] == 1 is land and 0 is water. Cells connect only up, down, left and right. The grid holds exactly one island (one connected group of land cells), the island has no lakes (no water enclosed by land), and everything outside the grid is water.

Every cell is a square of side 1. Return the perimeter of the island.

Examples

Input: grid = [[0,1,1],[0,1,0]]
Output: 8

Three land cells have 12 sides. Two pairs of cells share a side, and each shared side hides two edges: 12 - 4 = 8.

Input: grid = [[1],[1],[1]]
Output: 8

A bar of three cells: two long sides of length 3 and two ends of length 1.

Input: grid = [[1,1],[1,1]]
Output: 8

A 2 x 2 square has perimeter 8; the four inner borders do not count.

Constraints

Approaches

Follow-up

What if the grid could hold lakes, and the shore of a lake should not count? Then you need to know which water is open sea: flood it from the border first, and count only land edges facing sea or the outside. The use case "Coastline that faces the open sea" does exactly that.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…