BFS vs DFS: Visit Order, Shortest Paths and Memory
Both are ways to visit every vertex of a graph or tree by following its edges. Breadth-first search (BFS) spreads out in order of distance: it visits all vertices one edge away from the start, then those two edges away, and so on. Depth-first search (DFS) follows one path as far as it can go, and when it reaches a dead end it backs up and tries another path. BFS is implemented with a queue and DFS with a stack or recursion; on a graph stored as adjacency lists, both visit everything in time proportional to the number of vertices plus the number of edges. BFS is the usual choice for shortest paths in unweighted graphs, and DFS for exhaustively exploring every path or detecting cycles.
| Aspect | Breadth-first search (BFS) | Depth-first search (DFS) |
|---|---|---|
| Visit order | Nearest first (fewest edges from the start), spreading out layer by layer | Goes deep along one path, backs up at a dead end and moves on to the next path |
| Data structure used | Queue (first in, first out) | Stack (last in, first out) or recursive calls |
| Shortest paths | In an unweighted graph, the number of edges when a vertex is first reached is its shortest distance from the start | Not guaranteed: a vertex may be reached first by a roundabout path |
| Time complexity (V vertices, E edges) | O(V + E) with adjacency lists, O(V²) with an adjacency matrix | Same as BFS: O(V + E) with adjacency lists, O(V²) with an adjacency matrix |
| Memory use | Vertices to visit next are kept in the queue; with many branches, a whole layer of vertices sits in the queue at once, so it grows large | Written recursively, it only needs the vertices on the current path, so memory grows with the depth of the path; very deep searches can overflow the call stack |
| Whether a solution is found | Always found if there are finitely many vertices; even when the search space grows without limit, shallow solutions are found first | Always found in a finite graph if visited vertices are recorded; when paths can get deeper without limit, it may keep going down one path and never come back |
| Tree traversal order | Level order (level by level from the root, left to right) | Preorder, inorder and postorder |
| Typical uses | Shortest paths in unweighted graphs, the minimum number of moves in a maze, how many hops a network reaches | Exhaustive search of mazes and puzzles (backtracking), finding connected components and cycles, topological sorting |
Figures are typical orders of magnitude and vary by process generation and product.