Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Graphs and their traversals

By the end of this chapter, you'll be able to

  • Represent a graph with an adjacency list
  • Traverse a graph breadth-first with a queue
  • Find the shortest path in number of steps
  • Traverse a graph depth-first and mark visited vertices

Represent a graph

The most common way to represent a graph in Python is the adjacency list: a dictionary that maps each vertex to the list of its neighbours. Here are the bus lines of a small town, where each edge connects two consecutive stops:

network = {
    "Station": ["Market", "University"],
    "Market": ["Station", "Harbour", "Stadium"],
    "University": ["Station", "Hospital"],
    "Harbour": ["Market", "Beach"],
    "Stadium": ["Market", "Hospital"],
    "Hospital": ["University", "Stadium"],
    "Beach": ["Harbour"],
}

print(len(network), "stops")
print(sum(len(v) for v in network.values()) // 2, "connections")
print("Neighbours of the Market:", network["Market"])
7 stops
7 connections
Neighbours of the Market: ['Station', 'Harbour', 'Stadium']

The connections go both ways: each one appears twice in the dictionary, hence the division by 2. For a directed graph (one-way streets, follows), the edge is only recorded in one direction.

Breadth-first search

Breadth-first search (BFS) explores the graph in waves: first the start's neighbours, then the neighbours of those neighbours, and so on. It uses a queue (first in, first out), and a set of vertices already seen so as never to process the same one twice.

Since it reaches each vertex in the smallest possible number of steps, it gives the shortest path in number of edges:

from collections import deque

network = {
    "Station": ["Market", "University"], "Market": ["Station", "Harbour", "Stadium"],
    "University": ["Station", "Hospital"], "Harbour": ["Market", "Beach"],
    "Stadium": ["Market", "Hospital"], "Hospital": ["University", "Stadium"], "Beach": ["Harbour"],
}

def shortest_path(graph, start, goal):
    previous = {start: None}
    queue = deque([start])
    while queue:
        stop = queue.popleft()
        if stop == goal:
            path = []
            while stop is not None:
                path.append(stop)
                stop = previous[stop]
            return path[::-1]
        for neighbour in graph[stop]:
            if neighbour not in previous:
                previous[neighbour] = stop
                queue.append(neighbour)
    return None

print(shortest_path(network, "University", "Beach"))
print(shortest_path(network, "Station", "Stadium"))
['University', 'Station', 'Market', 'Harbour', 'Beach']
['Station', 'Market', 'Stadium']
  • deque is an efficient queue: popleft() removes the first item in O(1), whereas list.pop(0) would cost O(n);
  • previous plays two roles: it marks the stops already seen, and records where we came from to rebuild the path backwards;
  • each vertex and each edge is processed once: the traversal is O(V + E), for V vertices and E edges.

The Beach is reached in 4 stops: this is the shortest path, guaranteed by the order of the waves.

Step 5 of 5
Text description of the animation
  1. We put the start in the queue.
  2. We discover its neighbours: they are 1 stop away.
  3. Then the neighbours of the Station and the Hospital not seen yet: 2 stops away.
  4. The Harbour is discovered from the Market, 3 stops away. The Stadium was already seen.
  5. The Beach is reached in 4 stops: this is the shortest path, guaranteed by the order of the waves.

Depth-first search

Depth-first search (DFS) heads in one direction and goes as far as possible before backtracking. It is naturally written recursively. It does not give the shortest path, but it is enough to know what can be reached:

network = {
    "Station": ["Market", "University"], "Market": ["Station", "Harbour", "Stadium"],
    "University": ["Station", "Hospital"], "Harbour": ["Market", "Beach"],
    "Stadium": ["Market", "Hospital"], "Hospital": ["University", "Stadium"], "Beach": ["Harbour"],
    "Airport": ["Industrial zone"], "Industrial zone": ["Airport"],
}

def reachable(graph, vertex, seen=None):
    if seen is None:
        seen = set()
    seen.add(vertex)
    for neighbour in graph[vertex]:
        if neighbour not in seen:
            reachable(graph, neighbour, seen)
    return seen

from_station = reachable(network, "Station")
print(len(from_station), "stops reachable from the Station")
print(sorted(set(network) - from_station))
7 stops reachable from the Station
['Airport', 'Industrial zone']

The Airport and the Industrial zone form a separate component: no line connects them to the rest. Depth-first search reveals it in one pass.

Mini-lab: explore the networkPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: degrees of separation

In a small social network, each person has a list of friends. Write separation(network, a, b) that returns the minimum number of intermediaries between two people (0 if they are direct friends, -1 if they are not connected).

friends = {
    "Awa": ["Kofi", "Lina"], "Kofi": ["Awa", "Tariq"], "Lina": ["Awa"],
    "Tariq": ["Kofi", "Mei"], "Mei": ["Tariq"], "Sami": [],
}
Hint 1
Breadth-first search gives the number of edges of the shortest path. The number of intermediaries is that number minus 1.
Hint 2
Keep a distance dictionary: a discovered neighbour's distance is the current vertex's plus 1.
Show the solution and common mistakes
from collections import deque

friends = {
    "Awa": ["Kofi", "Lina"], "Kofi": ["Awa", "Tariq"], "Lina": ["Awa"],
    "Tariq": ["Kofi", "Mei"], "Mei": ["Tariq"], "Sami": [],
}

def separation(network, a, b):
    distance = {a: 0}
    queue = deque([a])
    while queue:
        person = queue.popleft()
        if person == b:
            return distance[b] - 1
        for friend in network[person]:
            if friend not in distance:
                distance[friend] = distance[person] + 1
                queue.append(friend)
    return -1

print(separation(friends, "Awa", "Kofi"), separation(friends, "Lina", "Mei"), separation(friends, "Awa", "Sami"))
0 3 -1

Lina and Mei are connected through Awa, Kofi and Tariq: 3 intermediaries. Sami has no friend in this network: -1.

Common mistakes:

  • Using depth-first search: it finds a path, not necessarily the shortest.
  • Returning the distance without subtracting 1: you would count links, not intermediaries. Always reread the statement to know what is being counted.

Summary

  1. 1A graph is a set of vertices connected by edges; in Python, an adjacency list (dictionary) represents it.
  2. 2Breadth-first search explores in waves with a queue, and gives the shortest path in number of edges.
  3. 3Depth-first search goes as far as possible before backtracking; it reveals what can be reached.
  4. 4Marking seen vertices avoids looping forever in cycles.
  5. 5A well-written traversal processes each vertex and each edge once: O(V + E).

Your progress is saved on this device. Create a free account to keep your progress on all your devices.