Number of Islands
Count the number of disconnected islands in a 2D binary grid by sinking land with DFS.
01The problem
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
| Input | Output | Why |
|---|---|---|
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]] | 3 | 3 distinct connected components of land. |
Constraints
m == grid.lengthn == grid[i].length1 <= m, n <= 300grid[i][j]is'0'or'1'.
02How to spot it
- "Number of connected components in a grid": Whenever you see an unvisited land cell
'1', increment island count and launch a DFS to sink all connected'1's into'0's. - In-place sinking: Changing
'1'to'0'guarantees no cell is visited twice and avoids allocating a separateboolean[][] visitedmatrix.
03Pseudocode
count = 0
for every cell:
if cell is '1':
count += 1
sink(cell) # island -> '0'
return count04Watch it work
binary grid
islands found
0
Scan grid row by row: upon finding '1', increment island count and sink entire island to '0'.
Pseudocode
- count = 0
- for every cell:
- if cell is '1':
- count += 1
- sink(cell) # island -> '0'
- return count
Variables
- count
- 0
05Step-by-step dry run
We trace the grid:
| Land cell found | Current count | Cells sunk by DFS | Remaining land |
|---|---|---|---|
(0, 0) | 1 | Sinks (0,0), (0,1), (1,0), (1,1) | (2,2), (3,3), (3,4) |
(2, 2) | 2 | Sinks (2,2) (isolated cell) | (3,3), (3,4) |
(3, 3) | 3 | Sinks (3,3), (3,4) | None |
Output: 3.
06Java solution
public class Solution {
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int count = 0;
int m = grid.length;
int n = grid[0].length;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (grid[r][c] == '1') {
count++;
sink(grid, r, c);
}
}
}
return count;
}
private static void sink(char[][] grid, int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') {
return;
}
grid[r][c] = '0';
sink(grid, r + 1, c);
sink(grid, r - 1, c);
sink(grid, r, c + 1);
sink(grid, r, c - 1);
}
public static void main(String[] args) {
char[][] grid = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
System.out.println(numIslands(grid));
}
}3
07Why it works
Each island is a maximal connected component in the grid graph. By iterating through all cells and triggering a sinking DFS only when encountering '1', the outer loop fires exactly once per island. The DFS then exhausts the entire component, marking every cell '0' so it is never counted again.
08Time and space
- Time complexity:
O(m * n). Every cell is visited at most a constant number of times (once by the nested loop, and once by the DFS). - Space complexity:
O(m * n)worst-case call stack recursion depth if the entire grid is one giant island.
09Edge cases
- Grid contains only water (
'0'): Returns 0. - Grid contains only land (
'1'): Returns 1. - Checkerboard pattern: Every
'1'is an isolated 1-cell island.
10Common mistakes
- Checking diagonals: Standard problem specifies 4 directions (horizontal and vertical only). Do not check diagonals unless explicitly asked.
11Other approaches
- Disjoint Set Union (Union-Find): Useful if land cells are added dynamically over time (LeetCode #305).
12In the interview
- Opening line: "I will iterate through the grid. When I find a
'1', I increment the count and launch a DFS that 'sinks' the island by turning all 4-directionally connected'1's into'0's."
13Quiz
Why is changing grid[r][c] from '1' to '0' during DFS helpful?
- (Recommended) It marks the cell as visited in-place, preventing infinite loops and eliminating the need for an auxiliary visited array
- It converts land into sea so fish can swim
- It reduces the time complexity from O(mn) to O(1)
- It sorts the grid alphabetically
Answer: It marks the cell as visited in-place, preventing infinite loops and eliminating the need for an auxiliary visited array.
14Solve it yourself
Open LeetCode #200 and submit the sinking DFS solution.