Graph Theory37 sections · 1633 units
Open in Course

DFS vs BFS Summary

When to use what?

DFS uses a stack (Last-In-First-Out) and explores as deep as possible. BFS uses a queue (First-In-First-Out) and explores level by level. DFS is simpler to code with recursion. BFS requires a queue but finds shortest paths in unweighted graphs. DFS is better for exhaustive search, cycle detection, and topological sorting.

BFS is better for shortest paths, level-order traversal, and finding connected components. If the problem asks for distance or shortest path, use BFS. If it asks to explore all possibilities or find cycles, use DFS.