You are given a row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.

Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100.

Determine the perimeter of the island.

Input & Output

Example 1 — Small Island
$ Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
💡 Note: The island has an irregular shape. Each land cell contributes edges that face water or boundaries. Total perimeter is 16.
Example 2 — Single Cell
$ Input: grid = [[1]]
Output: 4
💡 Note: A single land cell has 4 edges, all facing the boundary (water), so perimeter is 4.
Example 3 — Square Island
$ Input: grid = [[1,1],[1,1]]
Output: 8
💡 Note: A 2x2 square island. Each of the 4 cells contributes 2 edges to the perimeter (4×2=8).

Constraints

  • row, col ≤ 100
  • grid[i][j] is 0 or 1
  • There is exactly one island

Visualization

Tap to expand
Island Perimeter - Smart Edge Counting INPUT 0 1 0 0 1 1 1 0 0 1 0 0 1 1 0 0 = Land (1) = Water (0) Input Grid: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] ALGORITHM STEPS 1 Initialize Counter perimeter = 0 2 Scan Each Cell Loop through grid[i][j] 3 If Land Cell Found Add 4 (all edges) 4 Subtract Shared Edges -2 for each neighbor -2 +1 each Calculation: 7 land cells x 4 = 28 6 shared edges x 2 = 12 28 - 12 = 16 FINAL RESULT = Perimeter Edge Output: 16 OK - Perimeter = 16 All edges counted! Key Insight: Each land cell contributes 4 edges to the perimeter. When two land cells are adjacent, they share an edge that should not be counted. For each adjacent pair, subtract 2 from the total (1 edge from each cell). Formula: perimeter = 4 * landCells - 2 * sharedEdges TutorialsPoint - Island Perimeter | Smart Edge Counting Approach
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
285.0K Views
Medium Frequency
~15 min Avg. Time
4.3K 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