Graph Exploration Target: 15s
BFS = shortest path. DFS = exhaustive search. For grids: shortest → BFS, reachability → DFS, regions → either.
BFS vs DFS — DECISION GUIDE
────────────────────────────
USE BFS when:
□ Shortest path in unweighted graph
□ Level-by-level processing needed
□ Closest node satisfying condition
□ Minimum steps / moves / transforms
Examples: word ladder, shortest grid path, rotten oranges
USE DFS when:
□ Exhaustive search / enumerate all paths
□ Cycle detection, connected components
□ Topological sort
□ Tree traversals (inherently DFS)
□ Backtracking problems
Examples: number of islands, path exists, clone graph
COMPLEXITY: both O(V + E)
SPACE:
BFS: O(width) — queue stores entire level
DFS: O(height/depth) — stack stores path
GRID PROBLEMS:
"Shortest path" → BFS (always)
"Can you reach?" → DFS (simpler) or BFS
"Count regions" → DFS or BFS (both fine)
"All paths" → DFS with backtracking
Type it from memory. Go.