Skip to content
StackDecode
GraphsAnimated

Breadth-First Search (BFS)

Explore level by level with a queue.

Time

O(V + E)

Extra space

O(V)

Use it for

Shortest paths in unweighted graphs.

How it works

  1. Start at the chosen node and put it in a queue.
  2. Take the front node, visit it, and add all its unvisited neighbours to the back of the queue.
  3. Because the queue is first-in-first-out, nodes are visited level by level: all neighbours, then their neighbours.
  4. This gives shortest paths measured in number of edges.

Watch it run

Loading animation…