Island Perimeter (LeetCode 463): Solution and Explanation

Easy
Array
Depth First search
Breadth First search
Matrix

A grid of 0s (water) and 1s (land) holds exactly one island with no lakes. Every cell is a unit square. Return the length of the island's coastline, that is, the number of land-cell sides that touch water or the grid edge.

Intuition

Picture building a fence around each land cell separately. Every cell needs 4 pieces of fence, so the starting total is 4 times the number of land cells.

That overcounts. Wherever two land cells touch, there is a piece of fence on each side of the same edge, and neither of them is on the coast. Each such shared edge has to come out twice, once for each cell.

So the answer is 4 x land - 2 x shared. To find the shared edges without counting any of them twice, scan in row-major order and only look at the neighbour above and the neighbour to the left. The neighbour below and to the right will look back at this cell when their turn comes.

You do not need a DFS or BFS here, even though the problem talks about an island. The perimeter is a purely local property of each cell and its four neighbours.

Approach: Count sides minus shared edges

  1. Set perimeter = 0.
  2. Visit every cell in row-major order. Skip water.
  3. For a land cell, add 4.
  4. If the cell above exists and is land, subtract 2 for the edge they share.
  5. If the cell to the left exists and is land, subtract 2 for that shared edge.
  6. Return perimeter after the scan.

Step-by-step example

grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
  1. (0,1) is land: +4, perimeter = 4. Nothing above it or to its left.
  2. (1,0): +4 = 8. (1,1): +4 = 12, land above at (0,1) so -2 = 10, land to the left at (1,0) so -2 = 8. (1,2): +4 = 12, land to the left, -2 = 10.
  3. (2,1): +4 = 14, land above at (1,1), -2 = 12.
  4. (3,0): +4 = 16. (3,1): +4 = 20, land above at (2,1), -2 = 18, land to the left at (3,0), -2 = 16.
  5. 7 land cells give 28 sides and 6 shared edges remove 12, so the function returns 16.

Code: Python, Java, C++

1class Solution:
2    def islandPerimeter(self, grid: List[List[int]]) -> int:
3        perimeter = 0
4        for r in range(len(grid)):
5            for c in range(len(grid[0])):
6                if grid[r][c] == 1:
7                    perimeter += 4
8                    if r > 0 and grid[r - 1][c] == 1:
9                        perimeter -= 2
10                    if c > 0 and grid[r][c - 1] == 1:
11                        perimeter -= 2
12        return perimeter
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(rows x cols)

Each cell is visited once and checks at most two neighbours.

Space

O(1)

Only the running total is stored; the grid is read but never copied.

Other approaches

Count water-facing sides (time O(rows x cols), space O(1))

For each land cell, check all four directions and add 1 for every side that is out of bounds or faces water. It gives the same total and is just as fast, but it reads four neighbours per cell instead of two.

DFS from any land cell (time O(rows x cols), space O(rows x cols))

Flood the island from one land cell and add 1 every time the search steps into water or off the grid. It works and generalises to grids with several islands, but needs a visited marker and recursion stack.

Common mistakes

  • Checking all four neighbours and still subtracting 2 for each land neighbour. Every shared edge is then removed twice and the result comes out too small.
  • Subtracting 1 instead of 2 when you only look up and left. One shared edge hides a side of both cells.
  • Indexing grid[r - 1][c] without checking r > 0. In Python a negative index silently wraps to the last row.
  • Assuming the grid is square. Use the row count and the column count separately.

Frequently asked questions

Why subtract 2 for each pair of adjacent land cells?

Both cells counted the edge between them as one of their 4 sides. Since that edge is inside the island, both copies have to be removed.

Why does the problem rule out lakes?

A lake's shoreline would also be land touching water. With the counting formula it would simply be included, so the guarantee mostly keeps the definition of perimeter unambiguous: it is only the outer coastline.

Do I need DFS or BFS for Island Perimeter?

No. Every land cell's contribution depends only on its immediate neighbours, so a single scan over the grid is enough.

What is the time and space complexity?

O(rows x cols) time because each cell is checked once, and O(1) extra space because only a counter is kept.