Number of Islands – Solution & Complexity
Watch: Number of Islands with flood fill
Scan the grid. Each time you hit unvisited land, you've found a new island: count it, then flood-fill (DFS or BFS) every connected land cell so it isn't counted again. Every cell is visited once, so it's O(rows × cols).
Solution Walkthrough
Step 1: Understand the Grid
- Each
1cell is land and each0cell is water. - Land cells belong to the same island if they touch horizontally or vertically.
- Diagonal contact does not connect islands.
- We need to count connected groups of land.
- Each
Step 2: Naive Counting Is Not Enough
- Counting every land cell would overcount large islands.
- Once we discover one land cell, we must find all land connected to it.
- That whole connected component should add only one to the answer.
Step 3: Use DFS With a Visited Set
- Scan every cell in the grid.
- When an unvisited land cell is found, it starts a new island.
- Run DFS from that cell to mark every connected land cell as visited.
- Using a visited set avoids mutating the input grid.
Step 4: Count Island Starts
- Only increment the island count when the scan finds land that has not been visited.
- The DFS then visits the entire island, so future cells from the same island are skipped.
Step 5: Final Solution and Complexity
- Handle an empty grid before reading dimensions.
- Each cell is visited at most once.
- Time complexity is O(rows × cols).
- Space complexity is O(rows × cols) for the visited set and recursion stack in the worst case.