The Computing Series

The Concept

BFS and DFS answer the same question — “which nodes are reachable from a starting node?” — but in different orders and with different properties.

Property BFS DFS
Data structure Queue (FIFO) Stack (LIFO) or recursion
Traversal order Level by level (closest nodes first) One path fully before backtracking
Finds shortest path? Yes (in unweighted graphs) No
Memory usage O(width of graph) O(depth of graph)
Cycle detection Via visited set Via visited set

The choice between BFS and DFS is a choice about which order you need results. BFS gives you the nearest results first. DFS gives you complete paths before backtracking.


Read in the book →