Depth-First Search (DFS) — Recursion and Stack — Complete Beginner Guide
Learning Objectives
- Implement recursive DFS on a graph
- Rewrite DFS with an explicit stack
- Explain the role of visited and call stacks
- Contrast DFS path style with BFS waves
- Analyze time and space for DFS
What Is DFS?
Depth-first search plunges along one branch as far as possible before backtracking. It explores deep paths early instead of finishing an entire level first.
Recursion mirrors the backtracking naturally because the call stack remembers where to return.
def dfs_recursive(graph, node, visited=None):
if visited is None:
visited = set()
visited.add(node)
order = [node]
for neighbor in graph[node]:
if neighbor not in visited:
order.extend(dfs_recursive(graph, neighbor, visited))
return order
graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
print(dfs_recursive(graph, "A"))
Recursive DFS Anatomy
Every recursive solution needs two pieces.
| Piece | Purpose |
|---|---|
| Base case | Stop when node visited or leaf reached |
| Recursive case | Visit one unvisited neighbor deeper |
The visited set stops infinite loops on cyclic graphs.
Traversal Skeleton
def dfs_visit(graph, node, visited, out):
if node in visited:
return
visited.add(node)
out.append(node)
for neighbor in graph[node]:
dfs_visit(graph, neighbor, visited, out)
Iterative DFS with an Explicit Stack
The system call stack works, but deep graphs can overflow it. An explicit stack puts control in your hands.
def dfs_iterative(graph, start):
visited = set()
stack = [start]
order = []
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
# Reverse neighbors so leftmost explores first
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
return order
print(dfs_iterative(graph, "A"))
Pushing neighbors in reverse keeps the same left-to-right order as the recursive version.
Recursion Stack versus Data Stack
| Stack | Holds | Growth |
|---|---|---|
| Call stack | Frames of active calls | Depth of recursion |
| Explicit DFS stack | Nodes waiting to expand | Path length and branches |
| BFS queue | Nodes waiting to expand | Width of current level |
Deep narrow graphs stress the call stack. Wide graphs stress the BFS queue.
DFS for Paths and Cycles
DFS is natural for reachability, topological sort, connected components, and cycle detection.
def find_path(graph, start, goal, visited=None, path=None):
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start)
path = path + [start]
if start == goal:
return path
for neighbor in graph[start]:
if neighbor not in visited:
result = find_path(graph, neighbor, goal, visited, path)
if result is not None:
return result
return None
print(find_path(graph, "A", "F"))
Note that a DFS path is not guaranteed to be the shortest. Use BFS for fewest edges.
Complexity
| Metric | Cost | Notes |
|---|---|---|
| Time adjacency list | O(V plus E) | Each vertex and edge once |
| Time adjacency matrix | O(V squared) | Row scans |
| Space visited | O(V) | Tracks processed nodes |
| Space stack | O(h) to O(V) | Follows path depth |
BFS versus DFS
| Criteria | BFS | DFS |
|---|---|---|
| Frontier | Queue | Stack or recursion |
| Priority | Shallow first | Deep first |
| Shortest unweighted path | Yes | Not always |
| Memory on wide graphs | High | Lower |
| Typical uses | Levels, hops | Cycles, topo sort, components |
DFS Dry Runs and Cycle Ideas
Trace recursive DFS with an explicit stack drawing. Push the start node, pop it, mark it, then push neighbors so the first neighbor expands next. Keep a call stack column beside the data stack column to see how recursion mirrors iteration.
For cycle detection on an undirected graph, a visited neighbor that is not the immediate parent means a cycle. For directed graphs, track nodes on the current recursion path; revisiting a node still on that path closes a cycle.
| Context | Cycle Signal |
|---|---|
| Undirected | Neighbor visited and not parent |
| Directed recursion | Neighbor on current path stack |
| Union-find components | Union joins already connected ends |
Practice both flavors on a six-node graph with one deliberate cycle. If your code misses it, check whether you mark visited too late or ignore the parent rule. DFS subtleties hide in those two details more often than anywhere else.
Key Takeaways
💡
- DFS dives deep and backtracks instead of sweeping levels
- Recursion uses the call stack; iterative DFS uses your own stack
- Visited sets are required on graphs with cycles
- DFS time is O(V plus E) on adjacency lists
- Prefer BFS for shortest hop paths and DFS for structure probes
Practice Questions
- Rewrite the recursive DFS using an explicit stack and explain neighbor push order.
- Why can recursion overflow on a graph shaped like a long path?
- Give one task where DFS is clearly better than BFS and justify your choice.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions