Graph Traversal (DFS, BFS) - aloalgo.com
aloalgo.com
Beta
Problems
Cheat Sheet
Search
Ctrl+K
Light
Dark
System
Login
Graph Traversal (DFS, BFS)
Graph traversal means visiting all vertices in a graph. The two main approaches are Depth-First Search (DFS) and Breadth-First Search (BFS).
Depth-First Search (DFS)
Explore as deep as possible before backtracking. Uses a stack (explicitly or via recursion).
Recursive DFS
Copy
Iterative DFS
Copy
Breadth-First Search (BFS)
Explore level by level. Uses a queue. Guarantees shortest path in unweighted graphs.
BFS Template
Copy
BFS Shortest Path
Copy
DFS vs BFS
Aspect
DFS
BFS
Data Structure
Stack / Recursion
Queue
Order
Deep then backtrack
Level by level
Shortest Path
No
Yes (unweighted)
Space
O(height)
O(width)
Grid Traversal
DFS and BFS work the same on grids. Each cell is a vertex, adjacent cells are neighbors.
Copy
When to Use Which
Use DFS when:
Finding any path (not necessarily shortest)
Detecting cycles
Topological sorting
Exhaustive search (backtracking)
Use BFS when:
Finding shortest path in unweighted graph
Level-order processing
Finding nearest node with property X
Complexity
Both DFS and BFS have the same complexity:
Time:
O(V + E) where V = vertices, E = edges
Space:
O(V) for the visited set
Next: Dijkstra
Was this helpful?
Company
Contact Us
Privacy Policy
Practice
Study plan
All problems
Learn
Cheat Sheet
© 2026 aloalgo.com. All rights reserved.