Which graph problems can both DFS and BFS solve, and which one can only BFS solve?
Both find a spanning forest, the connected components, a path between two vertices and a cycle, each in $O(n + m)$. Only BFS finds a shortest path, one with the fewest edges, because its levels are the distances from the start; the path DFS finds is just some path.
| Problem | DFS | BFS |
|---|---|---|
| spanning forest, connected components | yes | yes |
| a path between two vertices, or whether one exists | yes | yes |
| a cycle, or whether the graph is a forest | yes | yes |
| a path with the fewest edges | no | yes |
On a map of Swiss towns and roads, a DFS asked for a route from Lucerne to Geneva may well return one over the Gotthard into Ticino, through Domodossola and back over the Simplon into the Valais, simply because those roads came first in the incidence lists, while a route via Bern takes far fewer road segments. DFS guarantees a path whenever one exists, nothing more. BFS reaches Geneva through the fewest segments. (A real route planner counts kilometres or minutes rather than segments, which needs an algorithm for weighted graphs such as Dijkstra's.)
When both would do, other things decide:
- Memory. Apart from the labels, DFS keeps the current route on its stack, so its extra memory grows with the depth of the search; BFS keeps up to a whole level in its queue, so it grows with the width.
- Recursion. A recursive DFS keeps that route on the call stack, which is small and fixed, so very deep graphs can overflow it; BFS's levels or queue live on the heap, which is much larger and grows as needed.
- What builds on it. DFS is the basis of further algorithms, such as finding a topological order of a directed acyclic graph.