Graph theory: vertices, edges and breadth-first search
About this lesson
A graph is a set of things joined in pairs: road maps, computer networks, friendships, web links. Follow one small graph, 5 vertices and 6 edges, as you count degrees, check the handshake lemma, store it as an adjacency list in Python, and watch breadth-first search find the distance from A to every vertex.
Vertices and edges
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.
>>> 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)Read the lesson step by step
Vertices and edges
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.
>>> 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)Degree: count the edges
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.
>>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ... ('B', 'D'), ('C', 'E'), ('D', 'E')] >>> sum(1 for e in E if 'B' in e) # edges at B 3The handshake lemma
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.
>>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ... ('B', 'D'), ('C', 'E'), ('D', 'E')] >>> deg = {v: sum(v in e for e in E) for v in 'ABCDE'} >>> deg {'A': 2, 'B': 3, 'C': 3, 'D': 2, 'E': 2} >>> sum(deg.values()), 2 * len(E) (12, 12)Adjacency list in Python
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.
>>> G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], ... 'C': ['A', 'B', 'E'], 'D': ['B', 'E'], 'E': ['C', 'D']} >>> G['B'] ['A', 'C', 'D'] >>> len(G['B']) # the degree of B 3 >>> sum(len(n) for n in G.values()) 12Paths and distance
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.
>>> G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], ... 'C': ['A', 'B', 'E'], 'D': ['B', 'E'], 'E': ['C', 'D']} >>> path = ['A', 'B', 'D'] >>> all(b in G[a] for a, b in zip(path, path[1:])) True >>> len(path) - 1 # edges on the path 2Breadth-first search starts
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.
>>> from collections import deque >>> dist = {'A': 0} >>> q = deque(['A']) >>> q deque(['A'])Visit the first layer
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.
>>> from collections import deque >>> G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], ... 'C': ['A', 'B', 'E'], 'D': ['B', 'E'], 'E': ['C', 'D']} >>> dist, q = {'A': 0}, deque(['A']) >>> u = q.popleft() >>> for v in G[u]: ... if v not in dist: ... dist[v] = dist[u] + 1 ... q.append(v) ... >>> dist, q ({'A': 0, 'B': 1, 'C': 1}, deque(['B', 'C']))Then the next layer
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.
>>> from collections import deque >>> G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], ... 'C': ['A', 'B', 'E'], 'D': ['B', 'E'], 'E': ['C', 'D']} >>> dist, q = {'A': 0, 'B': 1, 'C': 1}, deque(['B', 'C']) >>> for _ in range(2): ... u = q.popleft() ... for v in G[u]: ... if v not in dist: ... dist[v] = dist[u] + 1 ... q.append(v) ... >>> dist {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2} >>> q deque(['D', 'E'])Queue empty: done
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.
>>> from collections import deque >>> G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], ... 'C': ['A', 'B', 'E'], 'D': ['B', 'E'], 'E': ['C', 'D']} >>> def bfs(G, s): ... dist, q = {s: 0}, deque([s]) ... while q: ... u = q.popleft() ... for v in G[u]: ... if v not in dist: ... dist[v] = dist[u] + 1 ... q.append(v) ... return dist ... >>> bfs(G, 'A') {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2}The BFS tree
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.
>>> parent = {'B': 'A', 'C': 'A', 'D': 'B', 'E': 'C'} >>> len(parent), 5 - 1 # tree edges, n - 1 (4, 4) >>> 6 - len(parent) # left over: each closes a cycle 2Cost: O(V + E)
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).
>>> G = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], ... 'C': ['A', 'B', 'E'], 'D': ['B', 'E'], 'E': ['C', 'D']} >>> len(G) + sum(len(n) for n in G.values()) # pops + checks 17
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A graph has 7 edges. What do the degrees of all its vertices add up to?
Every edge has two ends and adds 1 to the degree of each, so the sum of degrees is always 2 × 7 = 14, whatever the number of vertices.
02In the lesson's graph, G['D'] is ['B', 'E']. What is the degree of D?
The degree is the number of edges touching a vertex, which is the length of its neighbour list: len(G['D']) is 2.
03Why does breadth-first search use a queue (first in, first out)?
Vertices leave the queue in the order they joined, so BFS finishes each layer before the next. That is why the first distance it gives a vertex is the fewest edges.
04BFS reaches 10 vertices in a connected graph. How many edges does its BFS tree have?
Every vertex except the start is reached by exactly one tree edge, so a tree on n vertices has n − 1 edges: 10 − 1 = 9.
05A graph has 100 vertices and 300 edges, stored as adjacency lists. Roughly how many basic steps does BFS take?
BFS pops each vertex once (100) and reads each list entry once (2 × 300 = 600), so about 700 steps: O(V + E), not V × E.
Glossary
- Graph
- A set of vertices together with a set of edges, each edge joining a pair of vertices.
- Vertex (plural vertices)
- One of the things a graph links, drawn as a dot. Also called a node.
- Edge
- A link between two vertices. In an undirected graph it goes both ways.
- Degree
- The number of edges that touch a vertex.
- Handshake lemma
- In every graph the degrees add up to twice the number of edges, because each edge has two ends.
- Adjacency list
- A way to store a graph: for each vertex, a list of its neighbours. In Python, a dict of lists.
- Path and distance
- A path walks from vertex to vertex along edges; the distance between two vertices is the fewest edges on any path.
- Breadth-first search (BFS)
- An algorithm that visits vertices layer by layer from a start vertex, using a queue, and finds the distance to each one.
Notes and sources
- Because the sum of degrees is always even, every graph has an even number of odd-degree vertices. Here they are B and C, both of degree 3.
- This graph is undirected: every edge goes both ways, so it sits in two neighbour lists. In a directed graph each edge has a direction, like a one-way street, and is stored once.
- 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.
- 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.
- BFS finds the paths with the fewest edges. When edges have different lengths, like roads, you need another algorithm, such as Dijkstra's.
- Lehman, Leighton & Meyer, Mathematics for Computer Science (MIT 6.042J), chapter 12 Simple Graphs
- MIT OpenCourseWare 6.042J Mathematics for Computer Science (Spring 2015)
- MIT OpenCourseWare 6.006 Introduction to Algorithms (Spring 2020), lecture 9: Breadth-First Search
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3rd ed., sections 22.1 and 22.2
- Python library: collections.deque
- Python tutorial: Data structures (lists and dictionaries)
- PEP 8: Indentation
Quiz Unlocks after the last step.