BFS vs DFS: breadth-first and depth-first search
Breadth-first search explores a graph in rings, nearest vertices first. Depth-first search follows one path as far as it can, then backs up. The only difference in the code is a queue versus a stack, but it changes what each search is good for.
On this page
Both algorithms answer the same basic question, “which vertices can I reach from here?”, and both take time proportional to the size of the graph. They visit vertices in very different orders, though, and that order is what makes BFS the tool for shortest paths in unweighted graphs and DFS the tool for cycles, orderings and structure.
Graphs in one paragraph
A graph is a set of vertices (also called nodes) joined by edges. Edges may be undirected (a road you can drive both ways) or directed (a one-way street, or “page A links to page B”). Programs usually store a graph as an adjacency list: for each vertex, the list of its neighbours. That takes space proportional to , the number of vertices plus the number of edges.
Try both on the same graph
Pick BFS or DFS and press play. Vertices turn amber when they are discovered and green when they are finished. The panel on the right shows the frontier: the queue for BFS, the call stack for DFS. Use “Add vertex” and “Add edge” to build your own graph; the run restarts whenever you change something.
Graph traversal visualiserDraw your own graph or start from a preset, then pick an algorithm and a start vertex.
- Current vertex
- Discovered / in the frontier
- Finished (settled)
- Edge skipped
Edit the graph as text
One edge per line: A B 4 joins A and B with weight 4 (weight optional, default 1). A line with one name adds a lone vertex.
Pseudocode
Frontier
Visit order
Distances
In this visualiser neighbours are always taken in alphabetical order, so every run is repeatable. Real programs use whatever order their adjacency lists happen to have, and the visit order changes with it. The set of reachable vertices does not.
Breadth-first search: a queue
BFS keeps a queue of discovered vertices waiting to be processed. It takes the vertex at the front, looks at its neighbours, and adds any it has not seen before to the back. Because the queue is first in, first out, every vertex at distance 1 from the start is processed before any vertex at distance 2, and so on: the search spreads out in layers.
That layering is the key fact about BFS. The first time BFS discovers a vertex, it has found a path to it with the fewest possible edges. Recording each vertex’s parent as you discover it therefore gives a shortest-path tree, and you can recover the shortest route to any vertex by following parents back to the start.
Worked example: BFS from A on the starting graph
The graph has edges A–B, A–C, B–D, B–E, C–F, C–G, E–H and E–F.
| Dequeue | New neighbours enqueued | Queue afterwards |
|---|---|---|
| A | B, C | B C |
| B | D, E | C D E |
| C | F, G | D E F G |
| D | none | E F G |
| E | H (F is already discovered) | F G H |
| F, G, H | none | empty |
Visit order: A, B, C, D, E, F, G, H. A is at distance 0; B and C at 1; D, E, F and G at 2; H at 3.
Depth-first search: a stack
DFS dives. From the current vertex it moves to the first undiscovered neighbour and continues from there, only coming back when it reaches a vertex with nothing new around it. It is most naturally written recursively, with the call stack doing the remembering; an explicit stack works too.
On the same graph DFS from A visits A, B, D, then backs up to B and goes to E, then F, then from F to C, from C to G, and finally back up to E for H: A, B, D, E, F, C, G, H. Notice that it reaches C through a long detour. DFS does not find shortest paths.
What it does provide is structure. Each vertex has a moment it is discovered and a later moment it is finished, and those intervals nest like parentheses. That property, studied in Tarjan’s 1972 paper, is behind many classic linear-time algorithms:
- Cycle detection. In a directed graph, meeting a vertex that is discovered but not yet finished means you have found a cycle.
- Topological sorting. Listing vertices in reverse order of finishing time gives an order in which every edge points forwards, for example an order in which to build software modules or take prerequisite courses.
- Connected and strongly connected components, bridges and articulation points.
- Maze generation and solving, and backtracking search in general.
BFS vs DFS at a glance
| Property | Breadth-first search | Depth-first search |
|---|---|---|
| Frontier | Queue (first in, first out) | Stack or recursion (last in, first out) |
| Order | By distance from the start, layer by layer | Along one path as deep as possible, then backtrack |
| Time | with adjacency lists | with adjacency lists |
| Extra memory | Proportional to the widest layer | Proportional to the longest path explored |
| Shortest paths (unweighted)? | Yes | No |
| Typical uses | Fewest hops, social-network “degrees of separation”, web crawling by distance, level-order traversal | Cycles, topological order, components, puzzles and backtracking |
Both run in time because each vertex is enqueued or entered once and each edge is examined a constant number of times (twice in an undirected graph, once from each end). With an adjacency matrix instead of lists, finding a vertex’s neighbours costs , and both searches become .
Pitfalls
- Mark vertices when you discover them, not when you dequeue them. If BFS only marks a vertex once it leaves the queue, the same vertex can be enqueued many times, which wastes time and memory.
- Deep recursion. Recursive DFS on a long path can overflow the call stack. For large graphs use an explicit stack.
- Disconnected graphs. A single search only reaches one component. To cover everything, start a new search from each vertex that is still undiscovered.
- Weighted edges. BFS counts edges, not distances. When edges have lengths, use Dijkstra’s algorithm, which is BFS with the queue replaced by a priority queue.
References
- R. E. Tarjan, “Depth-first search and linear graph algorithms”, SIAM Journal on Computing 1(2), 1972. doi:10.1137/0201010
- E. F. Moore, “The shortest path through a maze”, Proceedings of the International Symposium on the Theory of Switching, Harvard University Press, 1959. An early description of breadth-first search.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022. Chapter 20 covers elementary graph algorithms.
- “Breadth-first search”, Wikipedia.