Edexcel International Advanced Level Computer Science, point 21.2.1
The algorithm is explained and traced by hand in 15.2.3. In Unit 4 you must implement and use it in Python. It finds the shortest distance from a start vertex to every other vertex of a weighted graph with non-negative weights.
The graph
An adjacency list (18.2.6) as a dictionary of dictionaries (graph[a][b] is the weight of the edge from a to b):
graph = {
"A": {"B": 4, "C": 2},
"B": {"A": 4, "D": 5},
"C": {"A": 2, "D": 8, "E": 10},
"D": {"B": 5, "C": 8, "E": 2, "F": 6},
"E": {"C": 10, "D": 2, "F": 3},
"F": {"D": 6, "E": 3},
}
The algorithm in steps
- Distance to the start = 0; to every other vertex = infinity.
- No vertex has a "previous vertex" yet.
- Repeat: take the unvisited vertex with the smallest distance. Mark it visited.
- For each neighbour, if
distance[current] + weightis smaller than the neighbour's distance, update it and recordcurrentas its previous vertex. - Stop when all vertices are visited (or no reachable ones remain).
Version 1: simple (a list scan)
def dijkstra(graph, start):
distance = {v: float("inf") for v in graph}
previous = {v: None for v in graph}
distance[start] = 0
unvisited = set(graph)
while unvisited:
current = min(unvisited, key=lambda v: distance[v])
if distance[current] == float("inf"):
# the rest are unreachable
break
unvisited.remove(current)
for neighbour, weight in graph[current].items():
new = distance[current] + weight
if new < distance[neighbour]:
distance[neighbour] = new
previous[neighbour] = current
return distance, previous
Time: , because finding the minimum scans all unvisited vertices each time.
Version 2: with a priority queue (faster)
A heap (heapq) gives the smallest-distance vertex quickly, .
import heapq
def dijkstra_heap(graph, start):
distance = {v: float("inf") for v in graph}
previous = {v: None for v in graph}
distance[start] = 0
queue = [(0, start)] # (distance, vertex)
while queue:
dist, current = heapq.heappop(queue)
if dist > distance[current]:
# an out-of-date entry
continue
for neighbour, weight in graph[current].items():
new = dist + weight
if new < distance[neighbour]:
distance[neighbour] = new
previous[neighbour] = current
heapq.heappush(queue, (new, neighbour))
return distance, previous
An out-of-date entry (a vertex pushed earlier with a longer distance) is skipped with continue.
Recovering the path
Follow the previous links back from the target, then reverse.
def path_to(previous, target):
path = []
while target is not None:
path.append(target)
target = previous[target]
return path[::-1]
distance, previous = dijkstra(graph, "A")
print(distance)
# {'A': 0, 'B': 4, 'C': 2, 'D': 9, 'E': 11, 'F': 14}
# ['A', 'B', 'D', 'E', 'F']
print(path_to(previous, "F"))
Same results with dijkstra_heap.
Trace (version 1, from A)
| Visit | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| (start) | 0 | ∞ | ∞ | ∞ | ∞ | ∞ |
| A | 0 | 4 | 2 | ∞ | ∞ | ∞ |
| C (2) | 0 | 4 | 2 | 10 | 12 | ∞ |
| B (4) | 0 | 4 | 2 | 9 | 12 | ∞ |
| D (9) | 0 | 4 | 2 | 9 | 11 | 15 |
| E (11) | 0 | 4 | 2 | 9 | 11 | 14 |
| F (14) | 0 | 4 | 2 | 9 | 11 | 14 |
Stopping early (one target)
If you only need one destination, stop when it is taken from the queue:
def shortest(graph, start, goal):
distance = {v: float("inf") for v in graph}
previous = {v: None for v in graph}
distance[start] = 0
queue = [(0, start)]
while queue:
dist, current = heapq.heappop(queue)
# its distance is final
if current == goal:
return dist, path_to(previous, goal)
if dist > distance[current]:
continue
for neighbour, weight in graph[current].items():
new = dist + weight
if new < distance[neighbour]:
distance[neighbour] = new
previous[neighbour] = current
heapq.heappush(queue, (new, neighbour))
return None # unreachable
# (14, ['A', 'B', 'D', 'E', 'F'])
print(shortest(graph, "A", "F"))
Special cases and tests
| Test | Expected |
|---|---|
| Start equals target | Distance 0, path [start] |
| A vertex that can't be reached (a disconnected graph) | Distance stays infinity; shortest returns None |
| A graph with one vertex | {start: 0} |
| Two routes with equal length | Either path is correct |
| A direct edge longer than an indirect route | The indirect route is chosen |
| A directed graph | Only edges in the right direction are used |
g = {"A": {"B": 1}, "B": {"A": 1}, "C": {}} # C is isolated
d, p = dijkstra(g, "A")
print(d["C"]) # inf
print(shortest(g, "A", "C")) # None
g2 = {"P": {"Q": 10, "R": 3}, "Q": {}, "R": {"Q": 4}} # directed
# {'P': 0, 'Q': 7, 'R': 3}
print(dijkstra(g2, "P")[0])
The direct edge P to Q costs 10, but P to R to Q costs 3 + 4 = 7, so the indirect route wins.
Negative weights: Dijkstra's algorithm gives wrong answers, so check that all weights are non-negative.
Worked example
Task: a bus network has stops and journey times in minutes: Depot-Market 5, Depot-School 9, Market-School 3, Market-Park 8, School-Park 4. Find the quickest route from the Depot to the Park.
buses = {
"Depot": {"Market": 5, "School": 9},
"Market": {"Depot": 5, "School": 3, "Park": 8},
"School": {"Depot": 9, "Market": 3, "Park": 4},
"Park": {"Market": 8, "School": 4},
}
print(shortest(buses, "Depot", "Park"))
# (12, ['Depot', 'Market', 'School', 'Park'])
Working: from the Depot: Market 5, School 9. Visit Market (5): School becomes 5 + 3 = 8 (better than 9), Park 5 + 8 = 13. Visit School (8): Park becomes 8 + 4 = 12 (better than 13). Visit Park (12). The quickest journey is 12 minutes, via Market and School.
Exam tip: initialise distances to infinity (float("inf")) and the start to 0. Update only when the new distance is smaller, and record the previous vertex. Rebuild the path by following previous backwards, then reversing. Handle unreachable vertices. Say that weights must not be negative.
Check yourself
Why are distances set to infinity at the start?
No route is known yet, so any real distance found will be smaller and will replace it.
How is the path recovered from the previous dictionary?
Start at the target and follow the previous vertices back to the start, then reverse the list.
What is the advantage of using a priority queue?
It finds the unvisited vertex with the smallest distance quickly, making the algorithm faster on large graphs.
What happens to the distance of a vertex that can't be reached?
It stays at infinity.
Why does Dijkstra's algorithm fail with negative weights?
It assumes a vertex's distance is final once visited, which isn't true if a later negative edge could shorten it.