ENع
←Graph theory
Lesson 11 · Discrete maths

Graph theory: vertices, edges and breadth-first search

14 min11 steps5 questionsIntermediate
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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 11 · Interactive
01 / 11

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)
Loading figure…
or ← →
Read the lesson step by step
  1. 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)
  2. 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
    3
  3. The 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)
  4. 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())
    12
  5. Paths 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
    2
  6. Breadth-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'])
  7. 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']))
  8. 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'])
  9. 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}
  10. 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
    2
  11. Cost: 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

Quiz Unlocks after the last step.