LeetCode #463 Easy

Island Perimeter

Island Perimeter is LeetCode 463 (Easy). The grid holds 0 for water and 1 for land, and the land cells form one island. Each cell is a 1 × 1 square, and cells connect only up, down, left and right. Return the length of the island's outline.

  • The outline is made of unit sides: a side of a land cell counts if the other side of it is water or the edge of the grid.
  • The grid is at most 100 × 100, so one pass over every cell is cheap.
Constraints
  • 1 <= rows, cols <= 100
  • grid[r][c] is 0 (water) or 1 (land)
  • There is exactly one island, and it has no lakes (no water enclosed by land).
arraydepth-first searchbreadth-first searchmatrix
Open on LeetCode ↗
02

Intuition

A single land square has 4 sides. Put two land squares next to each other and the side between them disappears from the outline, and it disappears from both squares, since each had counted it.

So perimeter = 4 × (land cells) − 2 × (pairs of land cells that touch). Counting touching pairs is easy if each cell only looks up and to the left: every pair has exactly one cell that is lower or further right, so each pair is found once. Nothing about the island's shape, holes in the outline or turns needs tracing.

How to spot this pattern

The answer adds up small pieces (sides of squares) and only depends on which neighbours are land. When a total depends only on neighbour pairs, a plain scan with a local check beats a graph search.

03

Approach

Try it first

Before reading on, take a 2 × 2 block of land. Count its outline by hand, then count 4 per cell and see how many sides you must take away, and why it is 2 per touching pair.

1

Scan every cell, skip water

Loop over rows and columns. A water cell adds nothing to the outline, so move on. You do not need to find the island first, because every land cell gets visited by the scan anyway.

2

Add 4 for each land cell

Give every land cell its full 4 sides. This over-counts on purpose: a side shared with another land cell is in the total twice, once from each cell, and the next two checks remove it.

3

Take away 2 for land above and land to the left

If the cell above is land, subtract 2; if the cell to the left is land, subtract 2. Check r > 0 and c > 0 first, because row 0 has nothing above it and column 0 has nothing to its left; outside the grid acts like water.

4

Why looking only up and left is enough

Every touching pair is either one cell above the other or one beside the other. The lower or right-hand cell of the pair sees the other one when it looks up or left, and the other cell never looks down or right, so each pair loses exactly 2, once.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def islandPerimeter(self, grid: List[List[int]]) -> int:
▶3 rows, cols = len(grid), len(grid[0])
▶4 perimeter = 0
▶5 for r in range(rows):
▶6 for c in range(cols):
▶7 if grid[r][c] == 0:
▶8 continue
▶9 perimeter += 4
▶10 if r > 0 and grid[r - 1][c] == 1:
▶11 perimeter -= 2
▶12 if c > 0 and grid[r][c - 1] == 1:
▶13 perimeter -= 2
▶14 return perimeter
gridthis land cellno cell yetrunning total0start the scan with a total of 0
perimeter0
The scan goes row by row, left to right. Water cells add nothing, so only land cells get a step of their own. Each one adds 4 and then checks the cell above it and the cell to its left.
gridthis land cell+4up: noneleft: nonerunning total0+4=4row 0, column 1: +4, nothing shared
cell(0, 1)
perimeter4
Skipped 1 water cell before this one. Above and to the left are water or outside the grid, so all 4 sides count for now. If a later cell touches this one, that later cell will do the subtracting.
gridthis land cell+4up: noneleft: nonerunning total4+4=8row 1, column 0: +4, nothing shared
cell(1, 0)
perimeter8
Skipped 2 water cells before this one. Above and to the left are water or outside the grid, so all 4 sides count for now. If a later cell touches this one, that later cell will do the subtracting.
gridthis land cell+4up −2left −2running total8+0=8row 1, column 1: +4, −2 up, −2 left
cell(1, 1)
perimeter8
Land above and land to the left: each shared side (red) was counted by both cells, so each costs 2.
gridthis land cell+4up: noneleft −2running total8+2=10row 1, column 2: +4, −2 left
cell(1, 2)
perimeter10
The cell to the left is land. The side between them (red) is inside the island and was counted by both cells, so take 2 off.
gridthis land cell+4up −2left: nonerunning total10+2=12row 2, column 1: +4, −2 up
cell(2, 1)
perimeter12
Skipped 2 water cells before this one. The cell above is land. The side between them (red) is inside the island and was already counted once by that cell, so take 2 off: one for each cell.
gridthis land cell+4up: noneleft: nonerunning total12+4=16row 3, column 0: +4, nothing shared
cell(3, 0)
perimeter16
Skipped 2 water cells before this one. Above and to the left are water or outside the grid, so all 4 sides count for now. If a later cell touches this one, that later cell will do the subtracting.
gridthis land cell+4up −2left −2running total16+0=16row 3, column 1: +4, −2 up, −2 left
cell(3, 1)
perimeter16
Land above and land to the left: each shared side (red) was counted by both cells, so each costs 2.
gridthis land cellscan finishedrunning total16answer: 16 sides face water or the edge
land7
touching pairs6
perimeter16
7 land cells × 4 = 28, minus 2 × 6 touching pairs = 16. The blue sides are the outline; the dashed sides sit between two land cells and were taken out.
05

Count open sides

Look at all four neighbours of each land cell. A neighbour that is outside the grid or is water means that side is part of the outline, so add 1. Each outline side belongs to exactly one land cell, so nothing is counted twice and nothing has to be subtracted.

▶1class Solution:
▶2 def islandPerimeter(self, grid: List[List[int]]) -> int:
▶3 rows, cols = len(grid), len(grid[0])
▶4 perimeter = 0
▶5 for r in range(rows):
▶6 for c in range(cols):
▶7 if grid[r][c] == 0:
▶8 continue
▶9 for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
▶10 if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] == 0:
▶11 perimeter += 1
▶12 return perimeter
06

Common pitfalls

Subtracting 1 for a shared side

✗ Wrong
if r > 0 and grid[r - 1][c] == 1:
    perimeter -= 1
✓ Right
if r > 0 and grid[r - 1][c] == 1:
    perimeter -= 2

The shared side was added by both cells, so it is in the total twice. For [[1, 1]] subtracting 1 gives 7, but the outline of a 1 × 2 strip is 6.

Subtracting 2 for all four neighbours

✗ Wrong
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
    if is_land(r + dr, c + dc):
        perimeter -= 2
✓ Right
for dr, dc in ((-1, 0), (0, -1)):
    if is_land(r + dr, c + dc):
        perimeter -= 2

Both cells of a pair now find each other, so every shared side costs 4. [[1, 1]] returns 4 instead of 6. Look all four ways only if you subtract 1 each time, or count open sides instead.

Reading the row above without a bounds check in Python

✗ Wrong
if grid[r - 1][c] == 1:
    perimeter -= 2
✓ Right
if r > 0 and grid[r - 1][c] == 1:
    perimeter -= 2

In row 0, grid[-1] is the last row, not an error. For [[1], [1]] the top cell thinks the bottom cell is above it and subtracts 2 again, giving 4 instead of 6.

07

Edge cases

Land touching the grid border

Sides on the border are never subtracted, because there is no cell beyond them, so they stay in the outline as they should.

08

Complexity

Time
O(rows × cols)
Space
O(1)
Each cell is read once along with at most two neighbours. Only the running total is stored: no visited set, queue or recursion stack.
09

Island Perimeter FAQ

Do I need DFS or BFS to find the island first?

No. A DFS that adds 1 whenever it steps into water or off the grid also works, but it needs a visited mark and a recursion stack up to rows × cols deep. The scan touches the same cells with no extra memory, because water cells add nothing anyway.

What would change if the island had a lake, or there were several islands?

The counting code would still return the total length of every land/water border. With a lake, that includes the shore around the lake, which is why the problem rules lakes out: "perimeter" would no longer mean just the outer outline.

Is this related to Number of Islands?

Same grid, different question. Number of Islands needs a search because it asks which cells are connected; this problem only asks about neighbouring pairs, so a local check is enough.