What a graph is
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.
The degree of a vertex is the number of edges that touch it. B touches A, C and D, so B has degree 3. C also has degree 3, and A, D and E each have degree 2.
Add up all the degrees: 2 + 3 + 3 + 2 + 2 = 12. That is exactly twice the 6 edges, because every edge has two ends and adds 1 to the degree of each. This holds in every graph.
Storing a graph
To store a graph, give each vertex a list of its neighbours, the vertices one edge away. In Python that is a dict: G['B'] is ['A', 'C', 'D']. The lists hold 12 entries in all, because each edge is stored twice.
Breadth-first search
A path walks from vertex to vertex along edges. A → B → D uses 2 edges; A → C → E → D uses 3. The distance between two vertices is the fewest edges on any path, so A to D is 2.
Breadth-first search (BFS) finds the distance from A to every vertex. It keeps a queue: a line where items join at the back and leave from the front. Start with dist['A'] = 0 and A in the queue.
Take A from the front of the queue. Look at each neighbour: B and C have no distance yet, so each gets dist[A] + 1 = 1 and joins the back of the queue. Vertices one edge away come first.
Take B: A and C already have distances, so skip them; D is new, so dist[D] = 2. Take C: only E is new, so dist[E] = 2. The queue now holds D and E, two edges from A.
Take D, then E: all their neighbours already have distances, so nothing joins. The queue is empty and the while loop stops. From A, B and C are at distance 1; D and E at distance 2.
Trees and cost
Keep only the edge that first reached each vertex: A–B, A–C, B–D and C–E. They form a tree, a connected graph with no cycle, with 5 − 1 = 4 edges. Each other edge, B–C or D–E, closes a cycle.
BFS takes each vertex from the queue once (5 pops) and reads each neighbour list once (12 entries): 5 + 12 = 17 steps. The work grows in step with vertices plus edges, written O(V + E).
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.