Number of Islands
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Graphs.
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
Input: grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3
Three distinct connected groups of '1's.
Approach 1
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)
⏱ O(M * N * alpha(MN)) - alpha is the inverse Ackermann function.💾 O(M * N) - For the parent array in 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 |
Approach 2
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
⏱ O(M * N) - Each cell is visited constant number of times.💾 O(M * N) - Recursion stack in the worst case (all land).
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 |
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.