Imagine you're a surveyor tasked with measuring the coastline of a mysterious island! You have a grid map where each cell represents either land (1) or water (0).

Your mission: Calculate the total perimeter of the island - that is, count how many unit edges of land cells are exposed to water or the boundary.

Key Details:

  • Each cell is a 1ร—1 square
  • Cells connect horizontally and vertically only (no diagonal connections)
  • There's exactly one island (connected land cells)
  • The island has no lakes (no internal water)
  • The entire grid is surrounded by water

Goal: Return the perimeter as an integer representing the number of unit edges exposed to water.

Input & Output

example_1.py โ€” Basic Island
$ Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
โ€บ Output: 16
๐Ÿ’ก Note: The island perimeter is 16. Each land cell contributes edges that face water or boundaries. The island has an irregular shape with several external edges exposed to water.
example_2.py โ€” Single Cell Island
$ Input: grid = [[1]]
โ€บ Output: 4
๐Ÿ’ก Note: A single land cell has 4 edges, all of which are exposed to the boundary (treated as water), so the perimeter is 4.
example_3.py โ€” Linear Island
$ Input: grid = [[1,0],[1,0]]
โ€บ Output: 6
๐Ÿ’ก Note: Two vertically connected land cells. Top cell contributes 3 external edges, bottom cell contributes 3 external edges, but they share 1 internal edge, so total perimeter is 6.

Constraints

  • row == grid.length
  • col == grid[i].length
  • 1 โ‰ค row, col โ‰ค 100
  • grid[i][j] is 0 or 1
  • There is exactly one island in grid

Visualization

Tap to expand
๐Ÿ๏ธ Island Perimeter SurveyCoastline (Perimeter)16edges๐Ÿ” Method: Count land-to-water boundariesโ€ข Each land cell can contribute up to 4 perimeter edgesโ€ข Edges shared between land cells are internal (don't count)โ€ข Only edges facing water or boundaries count toward perimeter
Understanding the Visualization
1
Identify the Island
Locate all land cells (1s) in the grid - they form one connected island
2
Count External Edges
For each land cell, count edges that face water (0s) or grid boundaries
3
Sum Up Perimeter
Add all external edges to get the total island perimeter
Key Takeaway
๐ŸŽฏ Key Insight: The perimeter equals the total number of land cell edges that face water or grid boundaries. Use the mathematical approach (4 ร— land_cells - 2 ร— adjacent_pairs) for optimal efficiency!
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
89.0K Views
Medium Frequency
~12 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen