Island Perimeter - Problem
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]is0or1 -
There is exactly one island in
grid
Visualization
Tap to expand
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code