Web Analytics

🌲 DFS (Depth-First Search)

Intermediate ~30 min read

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

  1. Start with source vertex, mark visited
  2. For each unvisited neighbor:
    • Recursively call DFS on neighbor
    • Or push to stack (iterative)
  3. 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

Output
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:

  1. Algorithm: Stack/recursion-based deep traversal
  2. Time: O(V + E) - visit each vertex and edge once
  3. Space: O(V) - recursion depth or stack size
  4. Cycle Detection: Back edge detection reveals cycles
  5. Applications: Maze solving, topological sort, cycle detection
  6. 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!