← Knowledgebase

Graph search: BFS & DFS

Graphs and searching

A graph is a set of nodes joined by edges: road maps, friendships, web links, dependencies between tasks. The edges here go both ways (the graph is undirected), and two nodes joined by an edge are neighbours.

Searching a graph means visiting every node reachable from a start node, without visiting any node twice. The two classic ways differ only in which node they explore next.

Breadth-first search (BFS): a queue

  1. Put the start node in a queue and mark it discovered.
  2. Take the node at the front of the queue and process it.
  3. Add each of its neighbours that hasn't been discovered yet to the back of the queue, marking it discovered.
  4. Repeat until the queue is empty.

BFS spreads out in rings: everything one edge away, then two, and so on. So the first time it reaches a node is along a path with the fewest edges. Nodes are marked when they are added to the queue, not when processed, so no node is ever queued twice.

BFS from A on the example graph. Each d is the number of edges from A, and the highlighted edges form the BFS tree.

Depth-first search (DFS): a stack

  1. Visit the start node and push it on a stack.
  2. Look at the node on top. If it has an unvisited neighbour, visit that neighbour and push it: go deeper.
  3. If it has none, pop it off: back up to the node below it.
  4. Repeat until the stack is empty.

DFS follows one path as far as it goes before trying alternatives, like exploring a maze with one hand on the wall. The stack is exactly the path from the start to where you are. Written recursively, the call stack plays that role.

Reading the pictures

A not discovered yet B in the queue / on the stack C being processed D done

When a node has several neighbours to choose from, these pages always take them in alphabetical order. Any order gives a valid search; fixing one means each question has a single right answer.

Compared

BFSDFS
FrontierQueue (first in, first out)Stack (last in, first out)
ExploresRing by ringOne path as deep as possible, then backs up
Shortest paths?Yes, by number of edgesNo
Good forFewest-hops routes, levels, nearest matchesCycles, topological order, connected components, mazes
CostO(V + E): each node is processed once and each edge looked at twice

For shortest paths when edges have different lengths, see Dijkstra's algorithm.