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.
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?
Both count the same islands in O(m · n). The recursive DFS is shorter, so the steps, code and live demo follow it; the BFS code comes after the demo and is the safer choice on a grid that is one huge island.
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.
▶6if r < 0or r >= rows or c < 0or c >= cols or grid[r][c] != "1":
▶7return
▶8 grid[r][c] = "0"
▶9sink(r + 1, c)
▶10sink(r - 1, c)
▶11sink(r, c + 1)
▶12sink(r, c - 1)
▶13
▶14 count = 0
▶15for r inrange(rows):
▶16for c inrange(cols):
▶17if grid[r][c] == "1":
▶18 count += 1
▶19sink(r, c)
▶20return count
▶1classSolution {
▶2public:
▶3intnumIslands(vector<vector<char>>& grid) {
▶4int count = 0;
▶5for (int r = 0; r < grid.size(); r++) {
▶6for (int c = 0; c < grid[0].size(); c++) {
▶7if (grid[r][c] == '1') {
▶8 count++;
▶9sink(grid, r, c);
▶10 }
▶11 }
▶12 }
▶13return count;
▶14 }
▶15
▶16private:
▶17voidsink(vector<vector<char>>& grid, int r, int c) {
▶18if (r < 0 || r >= grid.size() || c < 0 || c >= grid[0].size() || grid[r][c] != '1') {
▶19return;
▶20 }
▶21 grid[r][c] = '0';
▶22sink(grid, r + 1, c);
▶23sink(grid, r - 1, c);
▶24sink(grid, r, c + 1);
▶25sink(grid, r, c - 1);
▶26 }
▶27};
▶1classSolution {
▶2publicintnumIslands(char[][] grid) {
▶3int count = 0;
▶4for (int r = 0; r < grid.length; r++) {
▶5for (int c = 0; c < grid[0].length; c++) {
▶6if (grid[r][c] == '1') {
▶7 count++;
▶8sink(grid, r, c);
▶9 }
▶10 }
▶11 }
▶12return count;
▶13 }
▶14
▶15privatevoidsink(char[][] grid, int r, int c) {
▶16if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') {
▶17return;
▶18 }
▶19 grid[r][c] = '0';
▶20sink(grid, r + 1, c);
▶21sink(grid, r - 1, c);
▶22sink(grid, r, c + 1);
▶23sink(grid, r, c - 1);
▶24 }
▶25}
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 below and to the right.
cell(2, 0)reached down from (1, 0)
depth3calls open
count1
Spreading down from (1, 0) reaches land at (2, 0). Turn (2, 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.
cell(2, 1)reached right from (2, 0)
depth4calls open
count1
Spreading right from (2, 0) reaches land at (2, 1). Turn (2, 1) into water first, so no neighbour can send the search back here. Then try down, up, right and left: there is land above.
cell(1, 1)reached up from (2, 1)
depth5calls open
count1
Spreading up from (2, 1) 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.
cell(0, 1)reached up from (1, 1)
depth6calls 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: there is land to the right.
cell(0, 2)reached right from (0, 1)
depth7calls open
count1
Spreading right from (0, 1) reaches land at (0, 2). Turn (0, 2) 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.
cell(0, 3)reached right from (0, 2)
depth8calls open
count1
Spreading right from (0, 2) reaches land at (0, 3). Turn (0, 3) into water first, so no neighbour can send the search back here. Then try down, up, right and left: there is land below.
cell(1, 3)reached down from (0, 3)
depth9calls open
count1
Spreading down from (0, 3) reaches land at (1, 3). Turn (1, 3) 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.
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.
cell(0, 2)now water
count1unchanged
The scan reaches (0, 2). 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.
cell(0, 3)now water
count1unchanged
The scan reaches (0, 3). 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.
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.
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.
cell(1, 3)now water
count1unchanged
The scan reaches (1, 3). 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.
cell(2, 0)now water
count1unchanged
The scan reaches (2, 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.
cell(2, 1)now water
count1unchanged
The scan reaches (2, 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.
result1islands
Answer 1. Every land cell was sunk exactly once, and the count went up only when the scan found untouched land, once per island.
grid2 × 2
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.
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.
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: every neighbour is water, already sunk or outside the grid, so this call returns. Land at (1, 1) touches only at a corner, which does not join it to this island.
cell(1, 1)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.
cell(1, 1)first cell
depth1calls open
count2
Turn (1, 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.
result2islands
Answer 2. Every land cell was sunk exactly once, and the count went up only when the scan found untouched land, once per island. The two cells touch only at a corner, which does not join them, so they are two islands.
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.
▶16if (x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] == '1') {
▶17 grid[x][y] = '0';
▶18queue.add(newint[] {x, y});
▶19 }
▶20 }
▶21 }
▶22 }
▶23 }
▶24return count;
▶25 }
▶26}
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.
Problem
Neighbours
Returns
Number of Islands (LeetCode 200)
4: up, down, left, right
how many islands
Find the number of islands (GFG)
8: also the diagonals
how many islands
Max Area of Island (LeetCode 695)
4
size of the largest island
Number of Provinces (LeetCode 547)
an adjacency matrix, not a grid
how 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.