Number of Islands
Master this topic with zero to advance depth.
Number of Islands
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.
Visual Representation
Grid:
1 1 0 0 0
1 1 0 0 0
0 0 1 0 0
0 0 0 1 1
Islands: 3 (Top-left, Middle, Bottom-right)Examples
Three distinct connected groups of '1's.
Level II: Intermediate (Union-Find)
Intuition
Each land cell '1' can be seen as a node. Adjacent '1's belong to the same connected component. We can use the Disjoint Set Union (DSU) to group these cells and count the number of resulting sets.
Thought Process
- Count total '1's in the grid (initial component count).
- Iterate through every cell. If it's a '1', check its Right and Down neighbors.
- If a neighbor is also '1', perform a
union. If they were in different sets, decrement the component count. - Return the final count of components.
Pattern: Disjoint Set Union (DSU)
Detailed Dry Run
Grid: [[1,1], [0,1]]
| Cell | Neighbors | Action | Sets |
|---|---|---|---|
| (0,0) | (0,1) is '1' | Union(0,1) | {0,1}, {1,1} (Count: 2) |
| (0,1) | (1,1) is '1' | Union(1,1) | {0,1,1,1} (Count: 1) |
| Result: 1 |
Level III: Optimal (DFS / BFS)
Intuition
Each cell '1' is a node, and adjacent '1's have edges. We can use a traversal to find Connected Components. When we find a '1', we launch a DFS/BFS to visit all reachable '1's and mark them as '0' ("sinking" the island) to avoid re-visiting.
Thought Process
- Iterate through every cell
(r, c). - If
grid[r][c] == '1':- Increment
count. - Launch DFS starting from
(r, c).
- Increment
- In DFS:
- Reached Water or Out of Bounds? Return.
- Mark current cell as '0' (visited).
- Recurse in 4 directions.
Pattern: Connected Components / Flood Fill
Detailed Dry Run
Grid: [[1,1], [0,1]]
| i, j | Val | Action | Count |
|---|---|---|---|
| 0,0 | '1' | Start DFS. Sink (0,0), (0,1), (1,1) | 1 |
| 0,1 | '0' | Skip | 1 |
| 1,1 | '0' | Skip | 1 |
| Final Count: 1 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.