Number of Islands
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Number of Islands
Given an 2D binary grid, return the number of islands. An island is surrounded by water and is formed by connecting adjacent land cells horizontally or vertically.
Examples
Input: grid = [["1","1","0"],["1","1","0"],["0","0","1"]]
Output: 2
Approach 1
Level I: DFS (Matrix Traversal)
Intuition
Traverse the grid. When we find '1' (land), increment the island count and use DFS to mark all connected land as '0' (visited).
⏱ O(M \cdot N)💾 O(M \cdot N)
Detailed Dry Run
Found '1' at (0,0). Increment count. DFS marks (0,1), (1,0), (1,1) as '0'. Continue.
Approach 2
Level III: Union-Find (Grid Logic)
Intuition
Treat each land cell as a node in a DSU. For every '1', union it with its neighbors. The number of islands is the number of land cells minus successful unions.
⏱ O(M \cdot N \cdot \alpha(M \cdot N))💾 O(M \cdot N)
Detailed Dry Run
Total '1's = 5. Union (0,0) and (0,1) -> success, count becomes 4. Union (0,0) and (1,0) -> success, count becomes 3.
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.