Depth-First Search
Go as deep as possible down one path before backing up.
- current
- land
- water
- ruled out
- active this step
Land at (0, 0)
A new island, so count becomes 1 and DFS starts sinking it.
VARIABLES
- cell
- (0, 0)
- count
- 1
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
DFS follows one branch to its end, then returns to the most recent choice. It uses recursion or an explicit stack, plus a visited set.
Why it matters
Connectivity, cycle detection, path existence and tree problems are often simplest as DFS.
Think of it like this
Exploring a cave: follow one tunnel to its end before trying the next.
Use it when
- Counting connected components or islands
- Detecting cycles
- Exploring every path, with backtracking
Avoid it when
- You need the shortest path in an unweighted graph - use BFS
- Very deep graphs with recursion in Python - use an explicit stack
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| DFS on a graph | O(V + E) | O(V) |
| DFS on an r × c grid | O(r × c) | O(r × c) |
| Recursion depth, worst case | - | O(V) |
Often confused with: BFS - it explores by distance; DFS explores by depth.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- On grids, mark cells visited by overwriting them if you may change the input
- Cycle detection in directed graphs needs three states: unvisited, in progress, done
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Counting diagonal neighbours when the prompt says 4-directional
- Recursing before marking the cell visited - infinite recursion
- Hitting the recursion limit on large grids
Edge cases to test
- An empty grid
- All water or all land
- A single row or a single column
Knowledge check
Quick check to lock in the intuition.
Why mark a cell as visited before exploring its neighbours?
Practice
Apply what you just watched on real interview problems.