π² DFS (Depth-First Search)
You're exploring a maze. Instead of checking all paths at the same level, you go deep down one path until you hit a dead end, then backtrack and try another. This is exactly what DFS (Depth-First Search) does - it explores as deep as possible before backtracking!
The Exploration Problem
DFS takes a different approach than BFS - it goes deep before going wide:
Real-World DFS Applications
- Maze Solving: Explore paths until finding exit
- Topological Sort: Order tasks with dependencies
- Cycle Detection: Find cycles in graphs
- Connected Components: Find all components
- Path Finding: Find any path (not necessarily shortest)
- Backtracking: Explore all possibilities
How DFS Works
DFS Algorithm
- Start with source vertex, mark visited
- For each unvisited neighbor:
- Recursively call DFS on neighbor
- Or push to stack (iterative)
- Backtrack when no more unvisited neighbors
Key insight: Stack/recursion naturally explores depth first!
See DFS in Action
Recursive vs Iterative
Recursive DFS
Advantages
- More intuitive and readable
- Natural backtracking via call stack
- Easier to implement
Iterative DFS
Advantages
- More control over the process
- Avoids stack overflow for deep graphs
- Uses explicit stack
Cycle Detection
Undirected Graph
Back edge (edge to already visited node that's not parent) = cycle
Directed Graph
Use three colors: WHITE (unvisited), GRAY (being explored), BLACK (finished)
Back edge to GRAY vertex = cycle!
The Complete Code
Click Run to execute your code
DFS Applications
Common Use Cases
- Maze Solving: Explore all paths
- Topological Sort: Order vertices in DAG
- Cycle Detection: Find cycles efficiently
- Connected Components: Find all components
- Path Finding: Find any path
- Tree Problems: Many tree algorithms use DFS
DFS vs BFS
When to Use Each
| Use DFS When | Use BFS When |
|---|---|
| Finding any path | Finding shortest path (unweighted) |
| Cycle detection | Level-order traversal |
| Topological sort | Finding vertices at distance K |
| Maze solving | Web crawling level by level |
| Backtracking problems | GPS navigation |
Summary
What You've Learned
DFS is a fundamental graph traversal algorithm:
- Algorithm: Stack/recursion-based deep traversal
- Time: O(V + E) - visit each vertex and edge once
- Space: O(V) - recursion depth or stack size
- Cycle Detection: Back edge detection reveals cycles
- Applications: Maze solving, topological sort, cycle detection
- Key insight: Stack/recursion naturally explores depth first
What's Next?
You've mastered DFS! Next, we'll explore Topological Sorting - ordering vertices in a directed acyclic graph, essential for build systems, course prerequisites, and task scheduling!
Enjoying these tutorials?