هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.
University Computer Science — Year 1 · السنة الجامعية 1
25Shortest Paths
From the Town Square to the Hospital, the shortest way is 6.3 kilometres long and takes nine minutes at the speed limits. Another way is a kilometre longer and takes a minute and a half less, because it uses the faster roads. Breadth-first search counts roads, neither metres nor seconds. This chapter weighs every road with a number, here its travel time or its length, and finds the paths of least total weight: from one place with Dijkstra’s algorithm when weights are not negative, with Bellman–Ford’s when they may be, in linear time when the graph is acyclic, and between all pairs of places at once with Floyd–Warshall’s.
You already know
The second book ran Dijkstra’s algorithm by hand on small maps. Binary heaps and priority queues were built in Chapter 18; topological orders and breadth-first search in Chapter 24; tables of subproblems in Chapter 23.
25.1 Weighted shortest paths
Definition 25.1 (Weight of a path, shortest path, weighted distance)
In a directed graph with a weight on each arc, the weight of a path is the sum of the weights of its arcs. The weighted distance is the infimum of the weights of the paths from to : if there is none, if there are paths of arbitrarily small weight. A shortest path from to is a path of weight .
An undirected road is two arcs of the same weight. The town’s roads carry their length in metres, or their travel time at the speed limit, rounded to the second.
def roads(weight="seconds"):
"""adj[u] is a list of (v, w); a one-way road gives one arc, any other road two.
The time of a road is its length at its speed limit, rounded to the second."""
adj = {int(p["place_id"]): [] for p in rows("places")}
for r in rows("roads"):
a, b = int(r["from_place"]), int(r["to_place"])
metres, kmh = int(r["length_m"]), int(r["speed_kmh"])
w = metres if weight == "metres" else round(metres * 3.6 / kmh)
adj[a].append((b, w))
if r["one_way"] == "0":
adj[b].append((a, w))
return adj
$ python wgraph.py
30 places, 105 arcs, speed limits [30, 50, 70] km/h
from the Station: [('Town Hall', 120), ('River Park', 35), ('Hill Park', 35)]
Definition 25.2 (Negative cycle)
A negative cycle is a cycle of negative weight. If one is reachable from and reaches , going round it again and again makes .
Proposition 25.3 (Subpaths of shortest paths)
Every subpath of a shortest path is a shortest path between its ends. And if there is no negative cycle, for every arc (the triangle inequality).
The proof is Exercise 25.9; it is cut and paste again, as in Chapter 23.
Definition 25.4 (Relaxation)
The algorithms keep an estimate , with and elsewhere at the start. To relax the arc is to set , and the parent of to , if that is smaller.
Every estimate is the weight of some path, the path of parents, so it never drops below the distance; and once , relaxing for the last arc of a shortest path to gives . The algorithms differ only in the order in which they relax arcs.
Definition 25.5 (Shortest-path tree)
A shortest-path tree from is a rooted tree on the vertices reachable from , rooted at , whose path from to each vertex is a shortest path.
25.2 Dijkstra’s algorithm with a heap
Method 25.6 (Dijkstra’s algorithm)
With non-negative weights: keep a set of settled vertices, at first empty. Repeatedly settle the unsettled vertex of smallest estimate, and relax every arc leaving it.
A binary heap gives the smallest estimate. When an estimate decreases, the program pushes a new entry rather than moving the old one (lazy deletion); the stale entry is skipped when it comes off the heap.
def dijkstra(adj, s):
"""(dist, parent, pops): pops counts entries taken off the heap, stale or not."""
dist, parent = {v: INF for v in adj}, {s: None}
dist[s] = 0
heap, settled, pops = [(0, s)], set(), 0
while heap:
d, u = heapq.heappop(heap)
pops += 1
if u in settled: # a stale entry: u was settled with a smaller key
continue
settled.add(u)
for v, w in adj[u]:
if d + w < dist[v]: # relax the arc u -> v
dist[v], parent[v] = d + w, u
heapq.heappush(heap, (dist[v], v))
return dist, parent, pops
def path(parent, v):
out = []
while v is not None:
out.append(v)
v = parent[v]
return out[::-1]
Theorem 25.7 (Dijkstra’s invariant)
With non-negative weights, every vertex has when it is settled. So at the end dist holds the distances, and the parents form a shortest-path tree.
The proof is Exercise 25.10: if were the first vertex settled with a wrong estimate, a shortest path to would leave the settled set somewhere, at an arc , and would have an estimate at most , smaller than ’s.
s, after settling s, then b, then a; the estimates are written beside the vertices. Settling b, at 1, lowers a from 4 to 3; settling a lowers c from 6 to 4. Then c is settled at 4 and t at 7.Each vertex is settled once and each arc relaxed once, so at most entries are pushed, plus the first; each push or pop costs , since . The total is . A heap with decrease-key (Chapter 18) keeps one entry per vertex, at the same cost, and less memory.
$ python dijkstra.py
fastest: 7290 m in 445 s, 7 roads, 35 pops
via North Bridge, River Park, Station, Hill Park, Market Hall, Museum
shortest: 6270 m in 539 s, 6 roads, 34 pops
via North Bridge, River Park, Town Hall, Fire Station, Clinic
figures/routes.py. They share their first two roads; then the fast one turns west through the Station onto faster roads, while the short one heads north.25.3 Negative weights and Bellman–Ford
Weights may be negative: a reward, a gain of height, a refund. Dijkstra’s algorithm then fails, because a vertex can be settled before a cheaper path reaches it through a negative arc.
a at 2 and relaxes , giving t the estimate 3. Settling b at 3, the arc lowers a to 1, but a is settled and its arcs are not relaxed again: t keeps 3, though its distance is 2.$ python dijkstra_neg.py
Dijkstra: {'s': 0, 'a': 1, 'b': 3, 't': 3}
true: {'s': 0, 'a': 1, 'b': 3, 't': 2}
Method 25.8 (Bellman–Ford algorithm)
Relax every arc, in any order; repeat, in rounds, until a round changes nothing. If round still changes an estimate, report a negative cycle.
def bellman_ford(adj, s):
"""(dist, parent, rounds), or None if a negative cycle is reachable from s."""
dist, parent = {v: INF for v in adj}, {s: None}
dist[s] = 0
for rounds in range(1, len(adj) + 1):
changed = False
for u in adj:
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v], parent[v] = dist[u] + w, u
changed = True
if not changed:
return dist, parent, rounds # a round without change: nothing will change
return None # still changing at round n: a negative cycle
Proposition 25.9 (Rounds of Bellman–Ford)
If no negative cycle is reachable from , then after rounds for every vertex that has a shortest path of at most arcs; so rounds suffice and round changes nothing. If a negative cycle is reachable from , every round changes some estimate.
Proof. Without a reachable negative cycle, every reachable has a shortest path that is simple, so of at most arcs. By induction on : if is a shortest path, after round (its prefix is a shortest path, Proposition 25.3), and round relaxes . Estimates never go below distances, so they stop changing. Conversely, if a round changes nothing, then for every arc; summing along a reachable cycle, where every estimate is finite, gives the weight of the cycle: no negative cycle is reachable. ∎
Each round costs , so the whole costs , far more than Dijkstra’s algorithm, but it accepts any weights.
$ python bellman_ford.py
roads in seconds: stable after 5 rounds out of at most 30, Hospital at 445 s
the negative arc: {'s': 0, 'a': 1, 'b': 3, 't': 2}
with the arc t -> b: None
Bellman published the method in 1958 as an algorithm for a routing problem; it also carries the name of Lester Ford, who studied the same kind of problem.
25.4 Shortest paths in a DAG
In a directed acyclic graph, relaxing the arcs leaving each vertex, the vertices taken in a topological order, gives all distances from in one pass, whatever the signs of the weights: when is reached, every arc entering has been relaxed, and by induction along the order . The cost is , the topological order included. The same pass with maxima in place of minima gives longest paths, a problem that is hard in general graphs but easy without cycles.
Definition 25.10 (Critical path)
A project is a set of tasks with durations and prerequisites, which form a DAG. The earliest start of a task is the largest total duration of a chain of tasks that must precede it; a critical path is a chain of tasks of largest total duration: its length is the shortest possible duration of the project.
def critical_path(tasks):
"""(start, length, path): start[t] is the earliest day t can start."""
start, via = {}, {}
for t in topological(tasks):
start[t], via[t] = 0, None
for before in tasks[t][1]: # relax the arc before -> t, keeping the maximum
end = start[before] + tasks[before][0]
if end > start[t]:
start[t], via[t] = end, before
last = max(tasks, key=lambda t: start[t] + tasks[t][0])
path = [last]
while via[path[-1]] is not None:
path.append(via[path[-1]])
return start, start[last] + tasks[last][0], path[::-1]
$ python dag_paths.py
earliest start: design 0, database 3, interface 3, import 8,
tests 8, manual 7, training 11, launch 12
project: 13 days; critical path: design > database > tests > training > launch
The manual can start on day 7 and has until day 9, two days before training must start on day 11: it has two days of slack. The tasks of the critical path have none.
25.5 All pairs: Floyd–Warshall
For the distances between all pairs, one can run Dijkstra’s algorithm from every vertex, at a cost of . A dynamic programme on the adjacency matrix is shorter to write and handles negative weights.
Method 25.11 (Floyd–Warshall algorithm)
Number the vertices . Let be the smallest weight of a path from to whose intermediate vertices are all less than . Then is if , for an arc and otherwise, and
The table is updated in place, in the outer loop; is the distance table.
def floyd_warshall(adj):
"""(order, d, nxt): d[i][j] is the distance from order[i] to order[j], nxt[i][j]
the index of the vertex after order[i] on a shortest path to order[j]."""
order = list(adj)
index = {v: i for i, v in enumerate(order)}
n = len(order)
d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
nxt = [[j if i == j else None for j in range(n)] for i in range(n)]
for u in adj:
for v, w in adj[u]:
if w < d[index[u]][index[v]]:
d[index[u]][index[v]], nxt[index[u]][index[v]] = w, index[v]
for k in range(n): # now paths may go through vertices 0..k
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
nxt[i][j] = nxt[i][k]
return order, d, nxt
def route(order, nxt, a, b):
i, j = order.index(a), order.index(b)
out = [a]
while i != j:
i = nxt[i][j]
out.append(order[i])
return out
The triple loop costs and the tables . On a dense graph, where is close to , it beats runs of Dijkstra by a logarithm and more; on a sparse one, such as roads, runs of Dijkstra cost about and win when is large. Updating in place is safe: in round , the entries and do not change, since a path to or from gains nothing by going through again, without negative cycles.
$ python floyd.py
30 x 30 table, 27000 steps of the triple loop; equal to 30 runs of Dijkstra: True
Town Square -> Hospital: 445 s, 7 roads, same route as Dijkstra: True
Hospital -> Town Square: 445 s, 7 roads, same route as Dijkstra: True
Town Square -> Library: 98 s, 1 road, same route as Dijkstra: True
Library -> Town Square: 204 s, 2 roads, same route as Dijkstra: True
Floyd published the algorithm in 1962 as a short procedure for shortest paths; the same year, Warshall proved the same loop correct for the reachability relation, with “or” and “and” in place of “min” and “”.
Definition 25.12 (Eccentricity, centre, diameter)
In a strongly connected weighted graph, the eccentricity of a vertex is its greatest distance to another vertex. A centre is a vertex of smallest eccentricity, the radius; the diameter is the greatest eccentricity, the largest distance between two vertices.
25.6 Exercises
Exercise 25.1 ★
In the graph drawn for Dijkstra’s algorithm, give the order in which the vertices are settled and the final distances, starting from a instead of s.
Solution
Solution of Exercise 25.1.
From a: settle a at 0, which gives c 1 and t 6; settle c at 1, which lowers t to 4; settle t at 4. The vertices s and b are not reachable: their distance is .
Exercise 25.2 ★
Run Bellman–Ford from on the arcs (2), (), (4), (2), (5), relaxed in this order in every round. Give the estimates after each round, and the number of rounds.
Solution
Solution of Exercise 25.2.
Round 1: and do nothing (infinite estimates), then , , . Round 2: , then . Round 3: . Round 4 changes nothing: four rounds, the last one quiet. The shortest path to , , has three arcs, and this order of relaxation needs a round for each.
Exercise 25.3 ★
Three vertices 0, 1, 2 have arcs (5), (2), (9), (1). Give the matrices , and of Floyd–Warshall.
Exercise 25.4 ★
In the project of Output 25.5, the database now takes 3 days. What are the new length and critical path?
Solution
Solution of Exercise 25.4.
The database ends on day 6, the interface on day 7: the tests now start on day 7, training on day 10 and the launch on day 11. The project takes 12 days, and the critical path is design, interface, tests, training, launch: shortening a critical task by two days saved only one, because another path became critical.
Exercise 25.5 ★★
This version fixes a vertex’s distance when it is first pushed. Explain the output and the difference with Listing 25.2.
def dijkstra_push(adj, s):
dist, heap = {s: 0}, [(0, s)]
while heap:
d, u = heapq.heappop(heap)
for v, w in adj[u]:
if v not in dist: # fixed at the first discovery
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return dist
{'s': 0, 'a': 5, 'b': 1}
Solution
Solution of Exercise 25.5.
a is reached first from s, at 5, and fixed; the path , of weight 2, is found later and ignored. Fixing at discovery is right for breadth-first search, where every arc has the same weight, so the first path found to a vertex has the fewest arcs. With weights, a vertex may only be fixed when it leaves the heap with the smallest key; until then, a cheaper path may still reach it.
Exercise 25.6 ★★
With the loop on innermost, 350 entries of the town’s table are wrong. Why?
for i in range(n):
for j in range(n):
for k in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d
wrong entries: 350 of 900
Solution
Solution of Exercise 25.6.
With innermost, the entry is computed once and for all, by trying every single intermediate vertex with the entries and as they are at that moment, which are not final when or comes later in the loops. A path that needs two intermediate vertices whose entries are computed too late is missed. With outermost, the entries and are complete for the vertices below before they are used.
Exercise 25.7 ★★
Compute the smallest weight of a path of at most arcs from to every vertex, with any weights, in , and test it.
Solution
Solution of Exercise 25.7.
def at_most_k(adj, s, k):
dist = {v: INF for v in adj}
dist[s] = 0
for _ in range(k):
before = dict(dist) # relax from the previous round only: one more arc
for u in adj:
for v, w in adj[u]:
if before[u] + w < dist[v]:
dist[v] = before[u] + w
return dist
By induction, after round , is the smallest weight of a path of at most arcs: such a path is either of at most arcs, or a path of at most arcs to some followed by . Relaxing from the copy before is what keeps one arc per round; relaxing in place could chain several arcs in one round, as Bellman–Ford does on purpose. The test compares with a brute-force enumeration of walks.
Exercise 25.8 ★★
Each arc has a capacity, for instance the height limit of a road. Find, from , the paths whose smallest capacity is as large as possible, by a variant of Dijkstra’s algorithm, and justify it.
Solution
Solution of Exercise 25.8.
def widest(adj, s):
width = {v: 0 for v in adj}
width[s] = float("inf")
heap, done = [(-width[s], s)], set()
while heap:
_, u = heapq.heappop(heap)
if u in done:
continue
done.add(u)
for v, c in adj[u]:
b = min(width[u], c) # the bottleneck of the path through u
if b > width[v]:
width[v] = b
heapq.heappush(heap, (-b, v))
return width
Extending a path can only lower its bottleneck, as adding a non-negative weight can only raise a length. So the proof of Theorem 25.7 works with “largest” for “smallest” and for : the unsettled vertex of largest width has its final width. The heap holds negated widths, since heapq pops the smallest.
Exercise 25.9 ★★
Prove Proposition 25.3.
Solution
Solution of Exercise 25.9.
Let be a shortest path from to and its piece from to . If a path from to were lighter, replacing by in would give a walk from to lighter than ; without negative cycles a walk can be shortened to a path no heavier, by cutting out its closed sub-walks, a contradiction. For the triangle inequality, a shortest path to followed by is a walk of weight , and is at most that (if , there is nothing to prove).
Exercise 25.10 ★★★
Prove Theorem 25.7.
Solution
Solution of Exercise 25.10.
Estimates are always weights of paths, so . Suppose is the first vertex settled with ; , and is reachable, or its estimate would be . Take a shortest path from to ; it starts in the settled set and ends outside it. Let be its first arc leaving the set. was settled with , and relaxed , so , using Proposition 25.3 and the non-negative weights after . So and has a smaller key than : it would have been settled first. Contradiction. For the tree: each vertex’s parent was settled before it, so the parent links have no cycle, and along them the weights add up to the distances.
Exercise 25.11 ★★★
In a weighted DAG, count the shortest paths from to every vertex in , and prove it.
Solution
Solution of Exercise 25.11.
def count_paths(adj, order, s):
"""order: a topological order of the vertices."""
dist, ways = {v: INF for v in adj}, {v: 0 for v in adj}
dist[s], ways[s] = 0, 1
for u in order:
if dist[u] == INF:
continue
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v], ways[v] = dist[u] + w, ways[u]
elif dist[u] + w == dist[v]:
ways[v] += ways[u]
return dist, ways
By induction along the topological order: when is taken, every arc entering has been relaxed, so , and ways[u] is the sum of ways[x] over the arcs with : each shortest path to is a shortest path to such an followed by the arc, in exactly one way. When an estimate drops, the count restarts from the new predecessor’s. Each arc is handled once: , with zero weights allowed, since there is no cycle.
Exercise 25.12 ★★★
Write a function that returns a negative cycle of a graph, as a list of vertices, or None, in .
Solution
Solution of Exercise 25.12.
def negative_cycle(adj):
"""Bellman--Ford from a virtual source with an arc of weight 0 to every vertex."""
dist, parent = {v: 0 for v in adj}, {v: None for v in adj}
last = None
for _ in range(len(adj)):
last = None
for u in adj:
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v], parent[v] = dist[u] + w, u
last = v
if last is None:
return None
for _ in range(len(adj)): # walk back n steps: we are now on the cycle
last = parent[last]
cycle, v = [last], parent[last]
while v != last:
cycle.append(v)
v = parent[v]
return cycle[::-1]
Starting every estimate at 0 is Bellman–Ford from a new vertex joined to all others by arcs of weight 0, so every cycle is reachable. If round still lowers the estimate of some vertex, the parent links contain a cycle: following them back steps from that vertex cannot avoid repeating a vertex. On a cycle of parent links, each estimate was set from the next one along the cycle, and summing the inequalities shows that its weight is negative. The cost is rounds of .
25.7 Problem: The centre of Brenmoor
Problem 25.1
Weekend problem — The centre of Brenmoor
Where in Brenmoor should the new ambulance station go, so that the farthest place is as close as possible? Travel times are those of Listing 25.1.
def eccentricities(order, d):
return {v: max(d[i]) for i, v in enumerate(order)}
$ python centre.py
Town Hall 349 s = 5.8 min, farthest South Bridge
River Park 364 s = 6.1 min, farthest Post Office
Station 399 s = 6.7 min, farthest Post Office
Old Mill 675 s = 11.2 min, farthest Post Office
Post Office 675 s = 11.2 min, farthest Old Mill
centre: Town Hall, radius 349 s; diameter 675 s = 11.2 min
Part I — Modelling.
- Compute the travel time of a road of 1360 m at 50 km/h, as the program does.
- Why does the Station have an arc of 120 s to the Town Hall but only 35 s to River Park?
- How many arcs does the town have, and why not 106?
- Why are the weights in whole seconds, and what does rounding cost on a route of seven roads?
- Why must a one-way road be an arc, not an edge, in this model?
- Could the weights be negative here? Which algorithms would still apply?
Part II — Dijkstra from the Town Square.
- Read the fastest and the shortest routes to the Hospital, and compare their lengths and times.
- Why did the search pop 35 entries for 30 places?
- Bound the number of pops in terms of and .
- Why do the parents form a tree, and why is it a shortest-path tree?
- Up to which place do the two routes agree, and what does Proposition 25.3 say of their first parts?
- Breadth-first search found a route of six roads to the Hospital in Output 24.5: compare it with the two routes.
Part III — All pairs.
- Prove by induction on that , as defined by the recurrence, is the smallest weight of a path from to with all intermediate vertices less than .
- Deduce that is the distance table.
- Show that the in-place update computes the same table.
- Explain how
nxtrebuilds a route, and whynxt[i][j] = nxt[i][k]is right. - Why do the Library and the Town Square have different distances in the two directions?
- Compare the costs of Floyd–Warshall and of 30 runs of Dijkstra on the town.
Part IV — The centre.
- Explain
max(d[i]): why is the distance from a place to itself harmless? - Read the centre, the radius and the diameter.
- Why does the Post Office appear as farthest for several places?
- Show that the diameter is at most twice the radius when every road is two-way.
- Does that bound hold for Brenmoor, with its one-way road?
- State the named result, the town’s centre and diameter, with its proof.
Solution
Solution of Problem 25.1.
1. , rounded to 98 s.
2. The road to the Town Hall is 1000 m at 30 km/h; the road to River Park is 680 m at 70 km/h.
3. 105: two arcs for each of the 52 two-way roads and one for the one-way road.
4. Integers make sums and comparisons exact, and ties really are ties. Each road’s time is off by at most half a second, so a route of seven roads by at most 3.5 s.
5. An edge could be driven both ways, and routes would use the one-way road against its direction.
6. No, times are positive. Bellman–Ford and Floyd–Warshall would still apply, but not Dijkstra’s algorithm.
7. The fastest route is 7290 m in 445 s, the shortest 6270 m in 539 s: 1020 m more, 94 s less.
8. 30 pops settle the places; the other 5 are stale entries, left behind when an estimate was lowered after its vertex had been pushed.
9. One push for the source and at most one per relaxed arc, so at most pushes and pops: 106 here.
10. The parent of was settled before , so following parents goes back in the order of settling and ends at : no cycle, a tree. By Theorem 25.7, its paths are shortest.
11. Up to River Park, by the North Bridge. The first part of each route is itself fastest, respectively shortest, to River Park; here the fastest and the shortest ways to River Park are the same.
12. It is the shortest route, by chance: fewest roads and fewest metres need not agree. The fastest route has seven roads.
13. For , a path without intermediate vertex is the empty path or a single arc. A best path from to with intermediate vertices less than avoids , and weighs , or passes through once (without negative cycles it need not pass twice), and splits into two paths with intermediate vertices less than , each best by cut and paste: .
14. With , every vertex may be intermediate: .
15. In round , the entries and do not change, since without negative cycles. So every entry read in round has its value of , whether it was updated already or not.
16. nxt[i][j] is the first step of a best path from to ; the route follows it until . When the path through wins, its first step is the first step of the best path from to .
17. Road 1 goes one way, from the Town Square to the Library, in 98 s; the way back needs two roads and 204 s.
18. Floyd–Warshall makes 27 000 steps of the triple loop. One Dijkstra run handles 135 vertices and arcs with heap operations of about 7 comparisons: about 30 runs 1000, of the same order. Floyd–Warshall’s loop is simpler; Dijkstra’s runs would win on a larger town, since grows faster than .
19. max(d[i]) is the largest distance from place ; the 0 of never wins when there are other places, all at positive distance.
20. The centre is the Town Hall, with radius 349 s (5.8 min); the diameter is 675 s (11.2 min), between the Old Mill and the Post Office.
21. The Post Office lies on the east edge of the map, the Old Mill in the south-west corner: they are far from most places, and from each other.
22. With symmetric distances, for any and and the centre : .
23. The proof uses , which the one-way road can break; the bound still holds here, , but it is checked, not proved.
24. The town’s centre and diameter: the Floyd–Warshall table is the distance table (questions 13–15), so the eccentricities computed from it are exact: the Town Hall is the centre, every place within 349 s of it, and no two places are more than 675 s apart. The ambulance station belongs at the Town Hall.