1dist = {'A': 0}2q = deque(['A'])3while q:4 u = q.popleft()5 for v in G[u]:6 if v not in dist:7 dist[v] = dist[u] + 18 q.append(v)BDACEq[0]q[1]q[2]q[3]q[4]0
Vertex blocks: the letter on top, a live value on the frontEdge traces: a lit edge is one the step is aboutQueue: q[0] is the front, where BFS takes the next vertexCounter and Python card: the sums and the BFS loopA graph with 5 vertices (A to E) and 6 edges. Each vertex shows a value on its front: its degree, then its neighbour list, then its distance from A. Tokens hop along dashed trails: each edge into the counter, each degree into the sum (2 + 3 + 3 + 2 + 2 = 12 = 2 × 6), and in breadth-first search a vertex from the front of the queue, a new distance along an edge, and the new vertex into the back of the queue. A tree with n vertices always has n − 1 edges. Add one more edge between two of its vertices and you create exactly one cycle.

What a graph is

  1. A graph is a set of dots, called vertices, joined by lines, called edges. Here 5 vertices, A to E, are joined by 6 edges. Graphs model road maps, computer networks and friendships: anything where things are linked in pairs.

Storing a graph

Breadth-first search

Trees and cost

Try it in the Python prompt

;; step 1/11 · Vertices and edges
>>> V = ['A', 'B', 'C', 'D', 'E']
>>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'),
...      ('B', 'D'), ('C', 'E'), ('D', 'E')]
>>> len(V), len(E)
(5, 6)

collections.deque removes from the front in constant time with popleft(). A plain list.pop(0) has to shift every other item, which gets slow for long queues. The code card indents by 2 spaces to fit; Python accepts any consistent indentation, and the PEP 8 style guide recommends 4.