Learning Outcome
After this lesson, you should be able to convert a grid into graph thinking and use DFS to mark one island at a time.
Problem Statement
Given a grid of land cells 1 and water cells 0, count how many groups of horizontally or vertically connected land exist.
| Input | Output | Why |
|---|---|---|
grid = [["1","1","0"],["1","0","0"],["0","0","1"]] | 2 | The top-left land group is one island and the bottom-right land cell is another island. |
Brute Force Approach
Compare every land cell with every other land cell to discover groups. This ignores locality and becomes unnecessarily slow.
Optimized Approach
Scan the grid once. When land is found, increment the count and DFS through its four-direction neighbors to mark that island.
Exact Pseudocode
count = 0
for each cell in grid:
if cell is land:
count += 1
dfs(cell)
return count
dfs(row, col):
if row or col is out of bounds:
return
if cell is water:
return
mark cell as water
dfs four neighbors
Reference Code
class Solution:
def numIslands(self, grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
def dfs(r, c):
if r < 0 or c < 0 or r == rows or c == cols or grid[r][c] != "1":
return
grid[r][c] = "0"
dfs(r + 1, c)
dfs(r - 1, c)
dfs(r, c + 1)
dfs(r, c - 1)
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
islands += 1
dfs(r, c)
return islandsSample Dry Run
| Step | State | Result |
|---|---|---|
| Cell (0,0) | Land found | islands = 1 |
| DFS from (0,0) | Marks (0,0), (0,1), (1,0) | First island is consumed |
| Cell (2,2) | Land found | islands = 2 |
| Finish scan | No more land | return 2 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(rows * cols) | Every grid cell is visited at most once. |
| Space | O(rows * cols) | DFS recursion can hold many cells in the worst case. |
Edge Cases
- Diagonal land is not connected unless the prompt says so.
- An all-water grid returns 0.
- A single large island can create deep recursion.
Interview Checklist
- Use four directions only.
- Mark visited before exploring neighbors.
- Do not count the same island twice.
FAQs
Why mark land as water?
It is an in-place visited marker that prevents revisiting the same island.
Can BFS solve this too?
Yes. DFS and BFS both work as long as each land cell is marked once.
What is the core pattern?
Grid DFS flood traversal.