DFS
Tactic
DFS explores one branch fully before returning to try alternatives. It can be written with recursion or an explicit stack.
The invariant is the visited state and the current path. In graph DFS, visited prevents cycles from causing infinite recursion. In tree DFS, the acyclic structure often makes visited unnecessary.
DFS is strongest when the answer depends on connected regions, paths, finishing times, or recursive substructure. It is not naturally shortest-path by edge count unless you explore every path or add more state.
Value
The value is low overhead exploration. DFS reaches deep structure quickly and stores only the active path plus visited state.
Direct complexity example
- Brute force: Start a fresh search from every node without remembering visited nodes: time in a graph.
- With this tactic: Mark visited nodes and traverse each edge a bounded number of times: time.
- Space: Space is for visited plus stack. In the worst case, depth can be .
Challenges this solves
- connected components
- cycle detection
- topological sort by finish time
- island counting
- tree recursion
- path existence
When to use it
Use this tactic when these conditions are true:
- you need to explore all reachable nodes
- depth or path context matters
- the graph can be marked visited
- recursive decomposition is clear
When not to use it
Reach for a different tactic when these warning signs appear:
- the problem asks for shortest unweighted path and BFS gives the first answer by level
- recursion depth is unsafe and an iterative stack is not planned
- edge weights require Dijkstra or Bellman-Ford
- you need level-by-level processing
Terminology clues
These prompt words often point toward this concept:
- DFS
- depth first
- connected component
- visited
- path exists
- island
- recursive traversal
- finish time
Problems that use it
- 98. Validate Binary Search Tree
- 100. Same Tree
- 110. Balanced Binary Tree
- 124. Binary Tree Maximum Path Sum
- 130. Surrounded Regions
- 133. Clone Graph
- 200. Number of Islands
- 211. Design Add and Search Words Data Structure
- 230. Kth Smallest Element in a BST
- 235. Lowest Common Ancestor of a BST
- 297. Serialize and Deserialize Binary Tree
- 332. Reconstruct Itinerary
- 543. Diameter of Binary Tree
- 572. Subtree of Another Tree
- 695. Max Area of Island
- 1192. Critical Connections in a Network
- 1448. Count Good Nodes in Binary Tree