programmingconcepts

§ 3.13 · Algorithms

BFS vs DFS

Two ways to explore a graph. Breadth-first goes level by level; depth-first follows one path to the end before backing up.

BFS and DFS both visit every node reachable from a start node in O(V + E) time. BFS uses a queue and explores level by level, so it finds fewest-edge paths. DFS uses a stack or recursion and goes deep first, which suits cycle detection, topological sorting and maze solving. They differ most in visiting order and memory use.

Both run in
O(V + E)
BFS keeps
A queue of the next level
DFS keeps
A stack of the current path
Shortest path
BFS only (unweighted)
Requires
Graph traversalStacks and queues
from collections import deque


def bfs(graph, start):
    seen = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph[node]:
            if nxt not in seen:
                seen.add(nxt)
                queue.append(nxt)
    return order


def dfs(graph, start):
    seen = set()
    stack = [start]
    order = []
    while stack:
        node = stack.pop()
        if node in seen:
            continue
        seen.add(node)
        order.append(node)
        for nxt in reversed(graph[node]):
            if nxt not in seen:
                stack.append(nxt)
    return order

Edit the graph

In the figure: click an empty spot to add a node, click one node and then another to connect or disconnect them, and select a node then press Delete to remove it. Up to 10 nodes.

step 0 / 0waitingcurrentdiscoveredvisited

Fig. 3.13. Breadth-first search on a tree visits it row by row. Switch to depth-first search and the same tree is visited one branch at a time.

The short answer

Breadth-first search (BFS) Depth-first search (DFS)
Waiting list Queue: first in, first out Stack, or the call stack when recursive
Visiting order Level by level, nearest first One branch to the end, then back up
Finds fewest-edge paths Yes No, just a path
Memory The widest level of the graph The longest path from the start
Time O(V + E) O(V + E)
Typical uses Shortest routes, friends-of-friends, web crawling by distance Cycle detection, topological sort, mazes, connected components

Graph traversal covers how each search works step by step. This page is about how they differ and how to choose.

Order: wide or deep

Both searches keep a waiting list of discovered nodes. The only difference is which node comes out next.

  • BFS takes the oldest discovery. Everything one edge from the start is visited before anything two edges away, so it moves outward in rings.
  • DFS takes the newest discovery. It keeps following the last thing it found, so it runs down one path until it hits a dead end, then backs up to the most recent fork.

On the tree in the figure, BFS reads it like a page, row by row. DFS traces the outline, finishing the whole left branch before touching the right.

Shortest paths: only BFS

Because BFS visits nodes in order of distance, the first time it reaches a node is along a path with the fewest edges. Record each node’s parent as you discover it and you can walk the shortest route back. DFS gives no such guarantee: it may reach a node next door to the start by a long detour.

That guarantee only counts edges. When edges have different weights, like road lengths, use Dijkstra’s algorithm, which is BFS with a priority queue in place of the plain queue.

Memory: wide or long

What each search holds at once depends on the shape of the graph:

  • BFS holds a whole level. In a tree where every node has 10 children, level 6 alone has a million nodes, and BFS keeps them all queued.
  • DFS holds one path, plus the unexplored siblings along it. On that same tree, six levels deep, it holds about 60 nodes.

So on wide, bushy graphs DFS is far lighter. On long, thin graphs, like a chain of a million nodes, it’s the reverse: DFS holds the whole chain, and a recursive DFS can overflow the call stack.

Which one to use

  1. Fewest steps from A to B? BFS. Puzzles, unweighted maps, degrees of separation.
  2. Need to visit everything and order doesn’t matter? Either. DFS is often simpler to write recursively.
  3. Does the graph have a cycle? What order do tasks with dependencies run in? DFS. Both answers come from noticing when a branch is finished.
  4. Huge or endless graph, and the target is probably close? BFS, so you don’t wander off down one endless branch. If memory is too tight for BFS, iterative deepening runs DFS with a depth limit of 1, then 2, then 3, getting BFS’s order with DFS’s memory.

Check yourself

Check yourself

A social network wants every user within 3 connections of you. Which search fits?

Check yourself

Every node in a tree has 3 children and the tree is 10 levels deep. Which search keeps fewer nodes in its waiting list?

Sources

  • Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, sections 22.2 and 22.3 (3rd edition).
  • Richard Korf, “Depth-first iterative-deepening: An optimal admissible tree search,” Artificial Intelligence 27, no. 1 (1985): 97–109.

Newsletter

One new concept each week, by email.

Signup opens soon.