LeetCode #200 Medium

Number of Islands

Number of Islands is LeetCode 200 (Medium). You are given an m x n grid of characters: '1' is land and '0' is water.

Return the number of islands. An island is a group of land cells joined horizontally or vertically (not diagonally), surrounded by water. Everything outside the grid counts as water.

  • The grid is at most 300 × 300, so each cell should be handled a constant number of times.
Constraints
  • m == grid.length, n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' (water) or '1' (land)
griddfsbfs
Open on LeetCode ↗
02

Intuition

An island is a group of connected land cells, so counting islands means counting those groups.

  • Count: scan the grid cell by cell. The first time you step on land from an island you have not seen, add 1.
  • Sink: then, straight away, turn that whole island into water, following every land neighbour up, down, left and right.

After the sink, no cell of that island is left as land, so the scan can never count it again. Every island is counted the moment the scan first reaches it, and only then, so the count is exact.

How to spot this pattern

Use scan-and-flood whenever a question asks how many connected groups a grid or graph has: islands, provinces, regions of the same colour. The same flood also answers "how big is each group" (Max Area of Island) if it returns a cell count.

03

Approach

Try it first

Before reading on: walk the first example by hand. When your scan reaches a land cell of an island you have already counted, how do you know not to count it again? What could you change in the grid to make that obvious?

1

Scan every cell

Go through the grid row by row. Water, and land that has already been sunk, is skipped at once. Only a land cell the scan has never touched means a new island.

2

Count it, then sink the island

Add 1 to count and call sink(r, c). The sink must finish before the scan moves on, so by the time the scan reaches the rest of this island it is all water.

3

Sink one cell and spread

sink(r, c) does three things in order:

  • return if (r, c) is outside the grid or is not '1';
  • set grid[r][c] = '0', before spreading, so two land neighbours never keep calling each other;
  • call sink on the four neighbours: down, up, right, left.
4

Return the count

When the scan ends, every island has been counted once and sunk. Return count.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numIslands(self, grid: List[List[str]]) -> int:
▶3 rows, cols = len(grid), len(grid[0])
▶4 
▶5 def sink(r, c):
▶6 if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1":
▶7 return
▶8 grid[r][c] = "0"
▶9 sink(r + 1, c)
▶10 sink(r - 1, c)
▶11 sink(r, c + 1)
▶12 sink(r, c - 1)
▶13 
▶14 count = 0
▶15 for r in range(rows):
▶16 for c in range(cols):
▶17 if grid[r][c] == "1":
▶18 count += 1
▶19 sink(r, c)
▶20 return count
1land0water0sunkscan01234011000111000200100300011islands0scan the grid row by row
grid4 × 5
count0
Start. The scan visits every cell from the top-left, row by row. Water is passed over. A land cell the scan reaches untouched must belong to an island not counted yet.
1land0water0sunkscan01234011000111000200100300011islands1new land at (0, 0) → island 1
cell(0, 0)untouched land
count1
Island 1. The scan has reached land that no earlier sink touched, so it belongs to a new island. Add 1, then sink the whole island before the scan moves on.
1land0water0sunkscan01234001000111000200100300011islands1sink (0, 0); land below, to the right
cell(0, 0)first cell
depth1calls open
count1
Turn (0, 0) into water first, so no neighbour can send the search back here. Then try down, up, right and left: there is land below and to the right.
1land0water0sunkscan01234001000101000200100300011islands1sink (1, 0); land to the right
cell(1, 0)reached down from (0, 0)
depth2calls open
count1
Spreading down from (0, 0) reaches land at (1, 0). Turn (1, 0) into water first, so no neighbour can send the search back here. Then try down, up, right and left: there is land to the right.
1land0water0sunkscan01234001000100000200100300011islands1sink (1, 1); land above
cell(1, 1)reached right from (1, 0)
depth3calls open
count1
Spreading right from (1, 0) reaches land at (1, 1). Turn (1, 1) into water first, so no neighbour can send the search back here. Then try down, up, right and left: there is land above. Land at (2, 2) touches only at a corner, which does not join it to this island.
1land0water0sunkscan01234000000100000200100300011islands1sink (0, 1); no land around it
cell(0, 1)reached up from (1, 1)
depth4calls open
count1
Spreading up from (1, 1) reaches land at (0, 1). Turn (0, 1) into water first, so no neighbour can send the search back here. Then try down, up, right and left: every neighbour is water, already sunk or outside the grid, so this call returns.
1land0water0sunkscan01234000000100000200100300011islands1(0, 1) was sunk → not a new island
cell(0, 1)now water
count1unchanged
The scan reaches (0, 1). It was land, but it belongs to an island that was already counted, and that island's sink turned it into water. So the check grid[r][c] == '1' fails and nothing is counted twice.
1land0water0sunkscan01234000000100000200100300011islands1(1, 0) was sunk → not a new island
cell(1, 0)now water
count1unchanged
The scan reaches (1, 0). It was land, but it belongs to an island that was already counted, and that island's sink turned it into water. So the check grid[r][c] == '1' fails and nothing is counted twice.
1land0water0sunkscan01234000000100000200100300011islands1(1, 1) was sunk → not a new island
cell(1, 1)now water
count1unchanged
The scan reaches (1, 1). It was land, but it belongs to an island that was already counted, and that island's sink turned it into water. So the check grid[r][c] == '1' fails and nothing is counted twice.
1land0water0sunkscan01234000000100000200100300011islands2new land at (2, 2) → island 2
cell(2, 2)untouched land
count2
Island 2. The scan has reached land that no earlier sink touched, so it belongs to a new island. Add 1, then sink the whole island before the scan moves on.
1land0water0sunkscan01234000000100000200000300011islands2sink (2, 2); no land around it
cell(2, 2)first cell
depth1calls open
count2
Turn (2, 2) into water first, so no neighbour can send the search back here. Then try down, up, right and left: every neighbour is water, already sunk or outside the grid, so this call returns. Land at (3, 3) touches only at a corner, which does not join it to this island.
1land0water0sunkscan01234000000100000200000300011islands3new land at (3, 3) → island 3
cell(3, 3)untouched land
count3
Island 3. The scan has reached land that no earlier sink touched, so it belongs to a new island. Add 1, then sink the whole island before the scan moves on.
1land0water0sunkscan01234000000100000200000300001islands3sink (3, 3); land to the right
cell(3, 3)first cell
depth1calls open
count3
Turn (3, 3) into water first, so no neighbour can send the search back here. Then try down, up, right and left: there is land to the right.
1land0water0sunkscan01234000000100000200000300000islands3sink (3, 4); no land around it
cell(3, 4)reached right from (3, 3)
depth2calls open
count3
Spreading right from (3, 3) reaches land at (3, 4). Turn (3, 4) into water first, so no neighbour can send the search back here. Then try down, up, right and left: every neighbour is water, already sunk or outside the grid, so this call returns.
1land0water0sunkscan01234000000100000200000300000islands3(3, 4) was sunk → not a new island
cell(3, 4)now water
count3unchanged
The scan reaches (3, 4). It was land, but it belongs to an island that was already counted, and that island's sink turned it into water. So the check grid[r][c] == '1' fails and nothing is counted twice.
1land0water0sunkscan01234000000100000200000300000islands3scan done → return 3
result3islands
Answer 3. Every land cell was sunk exactly once, and the count went up only when the scan found untouched land, once per island.
05

BFS version (queue)

On a new land cell, add 1, turn it into water and put it in a queue. Take cells off the queue one at a time; turn each land neighbour into water and add it to the queue, until the queue is empty.

▶1class Solution:
▶2 def numIslands(self, grid: List[List[str]]) -> int:
▶3 rows, cols = len(grid), len(grid[0])
▶4 count = 0
▶5 for r in range(rows):
▶6 for c in range(cols):
▶7 if grid[r][c] != "1":
▶8 continue
▶9 count += 1
▶10 grid[r][c] = "0"
▶11 queue = deque([(r, c)])
▶12 while queue:
▶13 i, j = queue.popleft()
▶14 for x, y in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
▶15 if 0 <= x < rows and 0 <= y < cols and grid[x][y] == "1":
▶16 grid[x][y] = "0"
▶17 queue.append((x, y))
▶18 return count
06

Common pitfalls

Marking a cell after spreading from it

✗ Wrong
sink(r + 1, c)
sink(r - 1, c)
sink(r, c + 1)
sink(r, c - 1)
grid[r][c] = "0"
✓ Right
grid[r][c] = "0"
sink(r + 1, c)
sink(r - 1, c)
sink(r, c + 1)
sink(r, c - 1)

Two side-by-side land cells call each other forever, because neither is marked yet when the other one checks it. The program ends with a stack overflow.

Comparing with the number 1

✗ Wrong
if grid[r][c] == 1:
✓ Right
if grid[r][c] == "1":

The grid holds characters. In Python, "1" == 1 is always False, so every cell looks like water and the answer is 0.

Counting diagonal neighbours

✗ Wrong
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1),
               (1, 1), (1, -1), (-1, 1), (-1, -1)):
✓ Right
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):

Here, land joins only up, down, left and right (the GFG version also counts diagonals). Spreading diagonally merges islands that should be separate; the third example would return 1 instead of 2.

07

Edge cases

One island filling a 300 × 300 grid

The recursive sink can go up to 90,000 calls deep. C++ and Java may overflow the stack, and Python needs a raised recursion limit. The BFS version below uses a queue and has no such limit.

08

Complexity

Time
O(m · n)
Space
O(m · n)
The scan visits every cell once, and each land cell is sunk once. The space is the recursion stack, which in the worst case (one long snake-shaped island) holds every cell.
09

Number of Islands and its look-alikes

The same scan-and-flood solves all of these; what changes is which neighbours count and what you return.

ProblemNeighboursReturns
Number of Islands (LeetCode 200)4: up, down, left, righthow many islands
Find the number of islands (GFG)8: also the diagonalshow many islands
Max Area of Island (LeetCode 695)4size of the largest island
Number of Provinces (LeetCode 547)an adjacency matrix, not a gridhow many groups
10

Number of Islands FAQ

What are the steps?
  • Scan: visit every cell in order.
  • Count: on a '1', add 1 to the count.
  • Sink: flood that island with DFS or BFS, turning every connected '1' into '0'.
  • Answer: the count when the scan ends.
  • Complexity: O(m · n) time and O(m · n) space in the worst case.
Can I solve it without changing the grid?

Yes. Keep a separate visited set (or a boolean grid) and check it instead of turning land into water. The steps are the same, at the cost of O(m · n) extra memory.