Depth First Search (DFS) Algorithm
Master graph traversal with DFS - from basics to advanced applications
What is Depth First Search?
DFS starts at a root node and explores each branch completely before moving to the next branch. This "depth-first" approach contrasts with Breadth First Search (BFS), which explores all neighbors at the current depth before moving deeper.
How DFS Works
Algorithm Steps
- Start: Mark the starting vertex as visited
- Explore: Visit an adjacent unvisited vertex
- Recurse: Recursively apply DFS to that vertex
- Backtrack: When no unvisited adjacent vertices remain, backtrack to the previous vertex
- Repeat: Continue until all reachable vertices are visited
Traversal Order Example
For a graph with vertices A-B-C-D-E connected as: A→B→D, A→C→E
DFS Order: A → B → D (backtrack) → C → E
BFS Order (for comparison): A → B → C → D → E
Implementation
Recursive Implementation (Python)
Iterative Implementation (Using Stack)
Time & Space Complexity
| Complexity Type | Value | Explanation |
|---|---|---|
| Time Complexity | O(V + E) | V = vertices, E = edges. Each vertex and edge is visited once. |
| Space Complexity (Recursive) | O(V) | Call stack can go as deep as the number of vertices |
| Space Complexity (Iterative) | O(V) | Explicit stack stores vertices |
Real-World Applications
Pathfinding
Finding paths in mazes, games, and navigation systems. DFS can find any path (not necessarily shortest).
Cycle Detection
Detecting cycles in graphs, useful for deadlock detection in operating systems and dependency analysis.
Topological Sorting
Ordering tasks with dependencies, used in build systems and course scheduling.
Connected Components
Finding all connected parts of a graph, used in network analysis and image segmentation.
Solving Puzzles
Sudoku, N-Queens, and other backtracking problems use DFS to explore solution spaces.
Web Crawling
Search engines use DFS-like algorithms to crawl websites by following links deeply.
Worked Examples
Example 1: Tree Traversal
Problem: Traverse a binary tree using DFS (in-order, pre-order, post-order).
Pre-order DFS (Root → Left → Right):
Use Case: Creating a copy of the tree, prefix expression evaluation
Example 2: Detecting Cycles
Problem: Detect if a directed graph contains a cycle.
DFS vs BFS Comparison
| Feature | DFS | BFS |
|---|---|---|
| Data Structure | Stack (or recursion) | Queue |
| Exploration | Goes deep first | Goes wide first |
| Memory Usage | Lower for deep graphs | Higher for wide graphs |
| Shortest Path | Not guaranteed | Guaranteed (unweighted) |
| Best For | Pathfinding, cycles, topological sort | Shortest path, level-order traversal |
Key Takeaways
- DFS explores depth before breadth using a stack
- Time complexity: O(V + E), Space: O(V)
- Can be implemented recursively or iteratively
- Excellent for cycle detection and topological sorting
- Not optimal for finding shortest paths
- Essential for backtracking algorithms