Number of Islands
Master this topic with zero to advance depth.
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
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).
Detailed Dry Run
Found '1' at (0,0). Increment count. DFS marks (0,1), (1,0), (1,1) as '0'. Continue.
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.
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.