Simple Algorithm
· 7 min read

BFS vs DFS: One Loop, Two Data Structures, Very Different Results

Breadth-first and depth-first search are the same few lines of code with one data structure swapped. Trade a queue for a stack and you change what the search finds first, how much memory it needs, and which problems it can solve.

Most graph algorithms start with a plain question: in what order should I visit things? There are two classic answers. Breadth-first search (BFS) visits everything one step away, then everything two steps away, like a ripple spreading from a stone. Depth-first search (DFS) picks a direction and keeps going until it hits a dead end, then backs up to the last junction and tries the next turn, the way you would explore a maze with a ball of string.

Both visit every reachable node exactly once, and both take the same time. They differ only in the order, and the order decides which one finds shortest paths, which one can spot a cycle, and which one runs out of memory on your input.

The comparison at a glance

Breadth-first search (BFS)Depth-first search (DFS)
Order of visitsLevel by level: every node at distance 1, then 2, then 3One path as deep as it goes, then back to the last junction
The to-do list is aQueue: first in, first outStack: last in, first out (usually the call stack of a recursive function)
TimeO(V+E)O(V + E)O(V+E)O(V + E)
Memory, besides the visited marksThe widest level of the graphThe longest path it follows
Finds the path with fewest edgesYes, to every node it reachesNo
Natural usesShortest paths when every edge counts the same, “nearest” questions, anything that spreadsCycle detection, topological order, connected components, backtracking
VV is the number of nodes (vertices) and EE the number of edges, with the graph stored as adjacency lists.

One loop, two data structures

Here is breadth-first search in Python, on a graph stored as a dictionary that maps each node to a list of its neighbors.

python
from collections import deque

def bfs(graph, start):
    # dist doubles as the visited set
    dist = {start: 0}
    queue = deque([start])
    while queue:
        u = queue.popleft()   # oldest first
        for v in graph[u]:
            if v not in dist:   # a new node
                dist[v] = dist[u] + 1
                queue.append(v)
    return dist

graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A', 'D'],
    'D': ['B', 'C', 'E'],
    'E': ['D'],
}
print(bfs(graph, 'A'))
# {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 3}

The result is the fewest edges from the start to each node.

And here is depth-first search, in the recursive form you will meet most often.

python
def dfs(graph, u, visited, order):
    visited.add(u)
    order.append(u)
    for v in graph[u]:
        if v not in visited:
            # go all the way down first
            dfs(graph, v, visited, order)

order = []
dfs(graph, 'A', set(), order)
print(order)
# ['A', 'B', 'D', 'C', 'E']

The same graph, visited in a different order.

Compare the two orders. BFS from A visits A, B, C, D, E: both of A’s neighbors before anything farther away. DFS visits A, B, D, C, E: it reaches D, two steps from A, before it has looked at A’s other neighbor.

The recursion hides the stack, but it is there. The chain of unfinished calls is the stack. You can write DFS with an explicit stack instead, and in outline it is the BFS loop with pop() in place of popleft(). The details need more care than that. Swap that one call in the code above and the loop still reaches every node, but not always in depth-first order, and it never records the moment a node is finished, which cycle detection and topological sorting both depend on. A faithful version keeps, for each node on the stack, its place in its own list of neighbors. Our lesson on Graphs, BFS & DFS builds one that matches the recursive search exactly.

Why BFS finds shortest paths

BFS reaches nodes in order of distance. Everything one edge from the start goes into the queue first. Their unvisited neighbors, two edges away, line up behind them. Because a queue is first in, first out, nothing at distance three can be handled until everything at distance two is done. So the first time BFS sees a node, it has arrived by a route with the fewest possible edges. That is why the code above can write dist[v] once and never revise it.

This is the fact about BFS you will use most, and it comes with a condition: every edge must count the same. Fewest edges is the shortest path only when all edges are equally long. On a road map, where edges have different lengths, the route with the fewest roads and the shortest route are different things, and you need Dijkstra’s algorithm, which is in essence BFS with the queue replaced by a priority queue.

DFS makes no such promise. It finds a path to each node, and which path depends on the order the neighbors happen to be listed in. In the example above, DFS reaches C by way of B and D, three edges, when C is one edge from A.

What DFS is good at

If BFS is about distance, DFS is about structure. Because it finishes everything below a node before it backs out of that node, it knows something BFS never does: which nodes it is still in the middle of exploring. A whole family of algorithms is built on that one piece of information.

  • Cycle detection. If DFS in a directed graph runs into a node it is still in the middle of exploring, it has found an edge that leads back up its own path, and that closes a cycle. No such edge, no cycle.
  • Topological sorting. To order tasks so that every prerequisite comes first, draw an edge from each prerequisite to the task that needs it, run DFS, and write each node down at the moment you finish it. Reverse the list and you have a valid order. Build systems and package managers need exactly this kind of ordering. (Kahn’s algorithm does the same job with a queue.)
  • Connected components. Start a search from every node not yet visited and count how many searches you needed. BFS does this equally well; DFS is just less code.
  • Backtracking. Solving a Sudoku or listing every permutation is a depth-first search through a tree of partial solutions: make a choice, go deeper, undo it when you get stuck.

The first two are worked through step by step in DAGs, Topological Sort & Strong Connectivity, and the last in Backtracking.

Memory: the practical difference

On paper both searches need O(V)O(V) memory in the worst case. In practice they fail on opposite shapes of graph.

BFS has to hold an entire level in its queue. On a graph that fans out quickly, say a puzzle where every position has ten possible moves, the level six moves deep holds a million positions, and BFS must store all of them to reach level seven. DFS on the same puzzle holds only the path it is on, plus the untried moves along it: a few dozen items.

DFS fails on depth instead. A recursive DFS uses one frame of the call stack for every node on its current path, and call stacks are small. Python stops at a recursion depth of 1,000 by default, so a recursive DFS on a simple chain of 5,000 nodes dies with a RecursionError even though the graph is tiny. Long, thin graphs (a linked list, a snake-shaped path through a grid) need the explicit-stack version, or BFS.

When the target is deep in a wide graph and you still want the shortest route to it, there is a hybrid called iterative deepening: run DFS limited to depth 1, then depth 2, then depth 3, until the target turns up. It revisits the shallow levels every round, which sounds wasteful and mostly isn’t, because in a tree that keeps branching the deepest level holds most of the nodes. Our AI course covers it in Uninformed Search.

How to choose

A short checklist covers most cases.

  1. You need the fewest steps, moves or hops. BFS. That includes “nearest” questions: the closest exit, the minimum number of moves, the degrees of separation between two people.
  2. You need an order, or you need to know about cycles. DFS. Dependencies, prerequisites, deadlocks.
  3. You are generating or testing combinations. DFS, in its backtracking form.
  4. You only need to reach everything, to count islands in a grid, fill a region or check that a network is connected. Either one. Pick BFS if the graph could be deep enough to overflow the call stack.
  5. Edges have different weights and you need the cheapest path. Neither. Use Dijkstra, or Bellman–Ford if some weights are negative.

One more signal is worth knowing. If a problem has several starting points and asks how far everything is from the nearest one, put all of them in the queue at the start. That is multi-source BFS, and it answers the question in a single pass.

Common questions

Is BFS faster than DFS?

Not in general. Both look at every node and every edge once, so both run in O(V+E)O(V + E) time. If you stop as soon as you find one particular target, whichever search happens to reach it first wins, and that depends on where the target is. BFS finds nearby targets sooner. DFS can get lucky on distant ones.

Can DFS find the shortest path?

A plain DFS, only by accident or by brute force. It returns the first path it stumbles on. You can make it try every path and keep the best, but that can take exponential time. Iterative deepening, described above, is the depth-first method that does guarantee the fewest edges. Otherwise use BFS, and for weighted edges use Dijkstra.

Does BFS work on weighted graphs?

It still visits every node, but the distances it reports count edges, not weights. Two special cases are fine: when all the weights are equal, and when every weight is 0 or 1, where a variant that uses a double-ended queue (known as 0-1 BFS) gives correct shortest paths.

Which one should I use on a tree?

On a tree the choice is about the order you want. DFS gives you the pre-order, in-order and post-order traversals. BFS gives you level order: the root, then its children, then their children. Both are covered in Binary Trees & Traversals.

Are BFS and DFS used in artificial intelligence?

All the time. Planning a route, solving a puzzle and choosing a move in a game are all searches through a graph of possible states. BFS and DFS are the starting points, and A* search improves on them by using an estimate of the remaining distance to decide where to look next.

How should I practice them?

Trace both by hand on the same small graph, writing down the queue or the stack after every step, until you can predict the next visit without thinking. Our lesson on Graphs, BFS & DFS has a simulation that steps through each search and shows the queue or the call stack as it changes. For where graphs fit among everything else, see our roadmap for learning data structures and algorithms.

Keep reading