Skip to main content
Back to problems
Leetcode
Medium
Matrices
Arrays
Graphs
Island Perimeter

Given a 2D grid of land and water, compute the total perimeter of the island formed by the land cells.

Acceptance 100%
Problem Statement

Problem

You are given a 2D grid where each cell is either land (1) or water (0). The grid contains exactly one island: a group of horizontally or vertically adjacent land cells.

Your task is to compute the perimeter of the island.

A land cell contributes to the perimeter for each of its four sides that touches water or the boundary of the grid.

Goal

Return the total perimeter of the island.

Input Format

  • A 2D integer grid grid with m rows and n columns.
  • grid[i][j] = 1 means land, and grid[i][j] = 0 means water.

Output Format

  • Return a single integer: the perimeter of the island.

Constraints

  • 1 <= m, n
  • The grid contains exactly one island.
  • The island is connected horizontally or vertically.
  • Each cell is either 0 or 1.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

16

Explanation

Each land cell contributes sides that touch water or the boundary. Summing all exposed sides gives a perimeter of 16.

Example 2

Input

grid = [[1]]

Output

4

Explanation

A single land cell has four sides, all touching the boundary.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.