The Decision Tree: BFS vs DFS
Pattern Recognition is Key
Most graph interview problems boil down to: "Which traversal do I use?" This decision tree will help you pick the right approach in seconds.
When to Use Which Algorithm
Adjacency List (preferred)
Space: O(V + E). Best for sparse graphs. Most interview problems use this.
Adjacency Matrix
Space: O(V^2). Best for dense graphs or when checking edge existence in O(1).
BFS Template
DFS Template
BFS vs DFS Traversal Comparison
Classic Graph Problems
Problem 1: Number of Islands (LeetCode 200) -- DFS Flood Fill
Problem 2: Course Schedule (LeetCode 207) -- Topological Sort
Problem 3: Clone Graph (LeetCode 133) -- BFS/DFS with Hash Map
Problem 4: Word Ladder (LeetCode 127) -- BFS Shortest Transformation
Problem 5: Pacific Atlantic Water Flow (LeetCode 417) -- Multi-source DFS
BFS Word Ladder Step-by-Step
DFS Islands Trace
Deep Dives
Deep Dive 1: Bidirectional BFS
For shortest-path problems where you know both start and end (like Word Ladder), bidirectional BFS searches from both ends simultaneously. This reduces time from O(b^d) to O(b^(d/2)) where b is the branching factor and d is the depth.
- Maintain two frontiers (sets), alternating expansion from the smaller one.
- When frontiers intersect, you have found the shortest path.
Deep Dive 2: A* Algorithm
A* extends Dijkstra with a heuristic function h(n) estimating distance to goal. It explores nodes with smallest f(n) = g(n) + h(n), where g(n) is actual cost from start. With an admissible heuristic (never overestimates), A* is optimal and often faster than plain Dijkstra.
Common Mistakes
Mistake #1: Not Marking Visited Before Pushing to Queue
Mistake #2: Infinite Loop in Undirected Graphs
Practice Problems
Easy: Flood Fill (LeetCode 733)
Given an image (2D array), a starting pixel, and a new color, flood-fill the connected region.
Hint
DFS from the starting pixel. Only visit pixels with the same original color.
Medium: Rotting Oranges (LeetCode 994) -- Multi-source BFS
In a grid, rotten oranges spread to adjacent fresh oranges each minute. How many minutes until all oranges are rotten?
Hint
Add all initially rotten oranges to the BFS queue at once (multi-source). Track levels for time.
Hard: Alien Dictionary (LeetCode 269)
Given a sorted dictionary of an alien language, derive the character ordering.
Hint
Compare adjacent words to build a directed graph of character ordering, then topological sort.
Quick Reference Guide
Key Takeaways
- BFS = shortest path in unweighted graphs, level-order traversal. Uses a queue.
- DFS = explore all paths, cycle detection, connected components. Uses recursion/stack.
- Always mark nodes as visited before adding to the queue (BFS) to avoid duplicates.
Related Topics
Time & Space Complexities
- BFS/DFS: O(V + E) time, O(V) space
- Dijkstra: O((V + E) log V)
- Topological Sort: O(V + E)
- Grid BFS/DFS: O(rows * cols)