Claviro

Traversal Algorithms

Depth-First Search (DFS)

Algorithm

Understanding Traversal Algorithms

BFS vs DFS

BFS: Explores level-by-level, using a queue. Good for shortest paths.

DFS: Goes deep into each branch, using a stack. Good for cycle detection.

Complexity

Time Complexity = O(V + E), Space Complexity = O(h)

About this concept

What to notice

DFS explores as far as possible along each branch before backtracking.

Why it matters

DFS is used for cycle detection, topological sorting, and finding strongly connected components.

Think about

How would you explore all rooms in a building by following each hallway as far as possible?

Formula & Application

Key Formula

Time Complexity = O(V + E), Space Complexity = O(h)

Use this formula to calculate the relationship between different variables in this concept.

Example

Detecting cycles in a graph by using DFS to find back edges.