Skip to content

Breadth-first search

Traverse a graph level by level from a start vertex with a queue, find shortest paths counted in edges with distances and parents, and show that BFS runs in O(V + E).

It opens on

Starting from A, which vertex is farther away in edges, D or F?

Why it matters

BFS finds the fewest hops in an unweighted network, such as degrees of separation, the fewest moves in a puzzle or the shortest route in a grid maze, and it is the skeleton of many graph algorithms; tracing its queue is a standard exam question.

Good to know first

  • Graphs and their representations: an adjacency list adj[u] holds u's neighbours, and the list entries add to 2E
  • Queues: first in, first out, with append and popleft on a deque

Step by step

  1. Level by level

    Run BFS from A with a queue, tracing the queue and the distances after each vertex is dequeued.

    Dequeue A and look at its neighbours B and C. Both are new, so each gets distance 1 and joins the queue. Then dequeue B; its neighbours are A, C and D, and only D is new, at distance 2.

    the BFS trace

    A common mix-up

    BFS goes as deep as it can along one path first.

    In fact: That is depth-first search; BFS finishes every vertex at distance d before any at distance d + 1.

  2. Shortest paths

    Record each vertex's parent during BFS and follow parents back to read a shortest path.

    B and C were found from A, so their parent is A. D was found from B.

    A common mix-up

    BFS's parent pointers give some path, not necessarily a shortest one.

    In fact: Every parent is one level closer to the start, so following them back gives a path of exactly dist[v] edges, a shortest one.

  3. Visited and cost

    Explain why BFS must skip vertices already found, and count its work to show it runs in O(V + E).

    The run counted 14. So BFS does V dequeues and 2E checks, each O(1) with a deque and a dictionary, O(V + E) in all.

    the work on this graph, in general

    A common mix-up

    BFS is O(V²) because each vertex may look at every other.

    In fact: With adjacency lists each vertex looks only at its own neighbours, so the total is O(V + E).

Try it

Run BFS from F. What are the distances of E, C and A?Answer

1, 2 and 3

Hint: F's only neighbour is E

From the parents, read the shortest path from A to D, and give its length.Answer

A, B, D, 2 edges

Hint: D's parent is B

A graph has 50 vertices and 120 edges, stored as adjacency lists. How many neighbour checks does a BFS that reaches every vertex make?Answer

240, which is 2E

Hint: Each edge is in two lists

Next C is dequeued. Which of its neighbours A, B and E is new, and at what distance?Answer

Only E, at distance 2, one more than C's 1; the queue becomes D, E.

Which vertex found E, and which found F?Answer

C found E, since C was dequeued before D; E found F.

Breadth-first search

30 minutes every month. No card.