---
title: "Shortest Paths"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 25
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/25-shortest-paths
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 25 — Shortest 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-bfs) 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-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](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#def-b1-heaps-binary-heap) and [priority queues](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#def-b1-heaps-pq) were built in [Chapter 18](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#ch-b1-heaps); [topological orders](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo) and [breadth-first search](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-bfs) in [Chapter 24](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#ch-b1-graph-traversals); tables of subproblems in [Chapter 23](https://one-course.com/books/computer-science/3/en/chapter/23-dynamic-programming#ch-b1-dynamic-programming).

## 25.1 Weighted shortest paths

**Definition 25.1 (Weight of a path, shortest path, weighted distance).**

In a [directed graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) with a weight $w(u, v)$ on each [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), the *weight* of a path is the sum of the weights of its [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). The *weighted distance* $\delta(s, v)$ is the infimum of the weights of the paths from $s$ to $v$: $+\infty$ if there is none, $-\infty$ if there are paths of arbitrarily small weight. A *shortest path* from $s$ to $v$ is a path of weight $\delta(s, v)$.

An undirected road is two [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) 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.

```python
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
```

***Listing 25.1.** The roads weighted by travel time code/bachelor-1/25-shortest-paths/listings/wgraph.py*

```
$ 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)]
```

***Output 25.1.** The road from the Station to the Town Hall is short, 1000 m, but limited to 30 km/h.*

**Definition 25.2 (Negative cycle).**

A *negative cycle* is a cycle of negative weight. If one is reachable from $s$ and reaches $v$, going round it again and again makes $\delta(s, v) = -\infty$.

**Proposition 25.3 (Subpaths of shortest paths).**

Every subpath of a [shortest path](#def-b1-shortest-paths-shortest) is a [shortest path](#def-b1-shortest-paths-shortest) between its ends. And if there is no [negative cycle](#def-b1-shortest-paths-negative), $\delta(s, v)
\leq \delta(s, u) + w(u, v)$ for every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $u \to v$ (the triangle inequality).

The proof is [Exercise 25.9](#exo-b1-shortest-paths-9); it is cut and paste again, as in [Chapter 23](https://one-course.com/books/computer-science/3/en/chapter/23-dynamic-programming#ch-b1-dynamic-programming).

**Definition 25.4 (Relaxation).**

The algorithms keep an estimate $\texttt{dist}[v] \geq \delta(s, v)$, with $\texttt{dist}[s] = 0$ and $+\infty$ elsewhere at the start. To *relax* the [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $u \to v$ is to set $\texttt{dist}[v] = \texttt{dist}[u] +
w(u, v)$, and the parent of $v$ to $u$, 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 $\texttt{dist}[u] = \delta(s, u)$, relaxing $u \to v$ for the last [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) of a [shortest path](#def-b1-shortest-paths-shortest) to $v$ gives $\texttt{dist}[v] =
\delta(s, v)$. The algorithms differ only in the order in which they [relax](#def-b1-shortest-paths-relaxation) [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph).

**Definition 25.5 (Shortest-path tree).**

A *shortest-path tree* from $s$ is a [rooted tree](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-rooted-tree) on the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) reachable from $s$, rooted at $s$, whose path from $s$ to each [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $v$ is a [shortest path](#def-b1-shortest-paths-shortest).

## 25.2 Dijkstra’s algorithm with a heap

**Method 25.6 (Dijkstra’s algorithm).**

With non-negative weights: keep a set of *settled* [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), at first empty. Repeatedly settle the unsettled [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) of smallest estimate, and [relax](#def-b1-shortest-paths-relaxation) every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) leaving it.

A [binary heap](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#def-b1-heaps-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.

```python
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]
```

***Listing 25.2.** Dijkstra’s algorithm with a [binary heap](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#def-b1-heaps-binary-heap) and lazy deletion code/bachelor-1/25-shortest-paths/listings/dijkstra.py*

**Theorem 25.7 (Dijkstra’s invariant).**

With non-negative weights, every [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $u$ has $\texttt{dist}[u] = \delta(s, u)$ when it is settled. So at the end `dist` holds the distances, and the parents form a [shortest-path tree](#def-b1-shortest-paths-tree).

The proof is [Exercise 25.10](#exo-b1-shortest-paths-10): if $u$ were the first [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) settled with a wrong estimate, a [shortest path](#def-b1-shortest-paths-shortest) to $u$ would leave the settled set somewhere, at an [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $x \to y$, and $y$ would have an estimate at most $\delta(s, u)$, smaller than $u$’s.

![Dijkstra’s algorithm from 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-shortest-paths/fig-2caa69ded49b.svg)

*Dijkstra’s algorithm from `s`, after settling `s`, then `b`, then `a`; the estimates are written beside the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) is settled once and each [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) relaxed once, so at most $m$ entries are pushed, plus the first; each push or pop costs $O(\log m) = O(\log n)$, since $m \leq n^2$. The total is $O((n + m) \log n)$. A heap with *[decrease-key](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#def-b1-heaps-decrease-key)* ([Chapter 18](https://one-course.com/books/computer-science/3/en/chapter/18-heaps-and-priority-queues#ch-b1-heaps)) keeps one entry per [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), 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
```

***Output 25.2.** The fastest and the shortest way from the Town Square to the Hospital; “pops” counts the entries taken off the heap, stale ones included.*

![The fastest route (solid, 445 s) and the shortest one (dashed, 6270 m), drawn from the data by 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.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-shortest-paths/fig-404569442dd2.svg)

*The fastest route (solid, 445 s) and the shortest one (dashed, 6270 m), drawn from the data by `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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) can be settled before a cheaper path reaches it through a negative [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph).

![Dijkstra settles a at 2 and relaxes a t, giving t the estimate 3. Settling b at 3, the arc b a lowers a to 1, but a is settled and its arcs are not relaxed again: t keeps 3, though its distance is 2.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-shortest-paths/fig-87280fe20193.svg)

*Dijkstra settles `a` at 2 and [relaxes](#def-b1-shortest-paths-relaxation) $a \to t$, giving `t` the estimate 3. Settling `b` at 3, the [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $b \to a$ lowers `a` to 1, but `a` is settled and its [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) 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}
```

***Output 25.3.** The listing of [Listing 25.2](#lst-b1-shortest-paths-dijkstra) on this [graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph).*

**Method 25.8 (Bellman–Ford algorithm).**

[Relax](#def-b1-shortest-paths-relaxation) every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), in any order; repeat, in *rounds*, until a round changes nothing. If round $n$ still changes an estimate, report a [negative cycle](#def-b1-shortest-paths-negative).

```python
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
```

***Listing 25.3.** Bellman–Ford, with a stop at the first quiet round code/bachelor-1/25-shortest-paths/listings/bellman_ford.py*

**Proposition 25.9 (Rounds of Bellman–Ford).**

If no [negative cycle](#def-b1-shortest-paths-negative) is reachable from $s$, then after $k$ rounds $\texttt{dist}[v] = \delta(s, v)$ for every [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $v$ that has a [shortest path](#def-b1-shortest-paths-shortest) of at most $k$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph); so $n - 1$ rounds suffice and round $n$ changes nothing. If a [negative cycle](#def-b1-shortest-paths-negative) is reachable from $s$, every round changes some estimate.

**Proof.** Without a reachable [negative cycle](#def-b1-shortest-paths-negative), every reachable $v$ has a [shortest path](#def-b1-shortest-paths-shortest) that is simple, so of at most $n - 1$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). By induction on $k$: if $s = v_0, \dots, v_k = v$ is a [shortest path](#def-b1-shortest-paths-shortest), $\texttt{dist}[v_{k-1}] = \delta(s, v_{k-1})$ after round $k - 1$ (its prefix is a [shortest path](#def-b1-shortest-paths-shortest), [Proposition 25.3](#prop-b1-shortest-paths-subpath)), and round $k$ [relaxes](#def-b1-shortest-paths-relaxation) $v_{k-1}
\to v$. Estimates never go below distances, so they stop changing. Conversely, if a round changes nothing, then $\texttt{dist}[v] \leq \texttt{dist}[u] + w(u, v)$ for every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph); summing along a reachable cycle, where every estimate is finite, gives $0 \leq$ the weight of the cycle: no [negative cycle](#def-b1-shortest-paths-negative) is reachable. ∎

Each round costs $O(n + m)$, so the whole costs $O(nm)$, 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
```

***Output 25.4.** Five rounds suffice on the town, the last one quiet; the [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $t \to b$ closes the cycle $b \to a \to t \to b$ of weight $-1$.*

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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-dag), relaxing the [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) leaving each [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) taken in a [topological order](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo), gives all distances from $s$ in one pass, whatever the signs of the weights: when $u$ is reached, every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) entering $u$ has been relaxed, and by induction along the order $\texttt{dist}[u] = \delta(s, u)$. The cost is $O(n + m)$, the [topological order](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo) included. The same pass with maxima in place of minima gives *longest* paths, a problem that is hard in general [graphs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) 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.

```python
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]
```

***Listing 25.4.** Earliest starts and a [critical path](#def-b1-shortest-paths-critical), in [topological order](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo) code/bachelor-1/25-shortest-paths/listings/dag_paths.py*

```
$ 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
```

***Output 25.5.** A small software project: delay any task of the [critical path](#def-b1-shortest-paths-critical) and the launch is delayed.*

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](#def-b1-shortest-paths-critical) have none.

## 25.5 All pairs: Floyd–Warshall

For the distances between all pairs, one can run Dijkstra’s algorithm from every [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), at a cost of $O(n (n + m) \log
n)$. A dynamic programme on the adjacency matrix is shorter to write and handles negative weights.

**Method 25.11 (Floyd–Warshall algorithm).**

Number the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $0, \dots, n - 1$. Let $D_k(i, j)$ be the smallest weight of a path from $i$ to $j$ whose intermediate [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) are all less than $k$. Then $D_0(i, j)$ is $0$ if $i = j$, $w(i, j)$ for an [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) and $+\infty$ otherwise, and

$$
D_{k+1}(i, j) = \min\bigl(D_k(i, j),\; D_k(i, k) + D_k(k, j)\bigr).
$$

The table is updated [in place](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-comparison-sort), $k$ in the outer loop; $D_n$ is the distance table.

```python
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
```

***Listing 25.5.** Floyd–Warshall, with a table of next [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) to rebuild the paths code/bachelor-1/25-shortest-paths/listings/floyd.py*

The triple loop costs $\Theta(n^3)$ and the tables $\Theta(n^2)$. On a dense [graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), where $m$ is close to $n^2$, it beats $n$ runs of Dijkstra by a logarithm and more; on a sparse one, such as roads, $n$ runs of Dijkstra cost about $n^2
\log n$ and win when $n$ is large. Updating [in place](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-comparison-sort) is safe: in round $k$, the entries $D(i, k)$ and $D(k, j)$ do not change, since a path to or from $k$ gains nothing by going through $k$ again, without [negative cycles](#def-b1-shortest-paths-negative).

```
$ 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
```

***Output 25.6.** All pairs in the town; the one-way road makes the return from the Library longer.*

Floyd published the algorithm in 1962 as a short procedure for [shortest paths](#def-b1-shortest-paths-shortest); 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-connected) [weighted graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-weighted), the *eccentricity* of a [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) is its greatest distance to another [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). A *centre* is a [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) of smallest eccentricity, the *radius*; the *diameter* is the greatest eccentricity, the largest distance between two [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph).

## 25.6 Exercises

**Exercise 25.1 ★.**

In the [graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) drawn for Dijkstra’s algorithm, give the order in which the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) are settled and the final distances, starting from `a` instead of `s`.

**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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) `s` and `b` are not reachable: their distance is $+\infty$.

**Exercise 25.2 ★.**

Run Bellman–Ford from $s$ on the [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $a \to c$ (2), $b \to a$ ($-1$), $s \to a$ (4), $s \to b$ (2), $b \to c$ (5), relaxed in this order in every round. Give the estimates after each round, and the number of rounds.

**Solution of Exercise 25.2.**

Round 1: $a \to c$ and $b \to a$ do nothing (infinite estimates), then $a = 4$, $b = 2$, $c = 7$. Round 2: $c = 6$, then $a = 1$. Round 3: $c = 3$. Round 4 changes nothing: four rounds, the last one quiet. The [shortest path](#def-b1-shortest-paths-shortest) to $c$, $s \to
b \to a \to c$, has three [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), and this order of relaxation needs a round for each.

**Exercise 25.3 ★.**

Three [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) 0, 1, 2 have [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $0 \to 1$ (5), $1 \to 2$ (2), $0 \to 2$ (9), $2 \to 0$ (1). Give the matrices $D_0$, $D_1$ and $D_2$ of Floyd–Warshall.

**Solution of Exercise 25.3.**

Rows are the sources, columns the targets, $\infty$ for no path:

$$
D_0 = \begin{pmatrix} 0 & 5 & 9 \\ \infty & 0 & 2 \\ 1 & \infty & 0 \end{pmatrix},\quad
D_1 = \begin{pmatrix} 0 & 5 & 9 \\ \infty & 0 & 2 \\ 1 & 6 & 0 \end{pmatrix},\quad
D_2 = \begin{pmatrix} 0 & 5 & 7 \\ \infty & 0 & 2 \\ 1 & 6 & 0 \end{pmatrix},
$$

and $D_3$ adds $D(1, 0) = 2 + 1 = 3$. Going through 0 helps only paths starting at 2, the only [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) with an [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) into 0: $2 \to 0 \to 1$.

**Exercise 25.4 ★.**

In the project of [Output 25.5](#out-b1-shortest-paths-dag), the database now takes 3 days. What are the new length and [critical path](#def-b1-shortest-paths-critical)?

**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](#def-b1-shortest-paths-critical) 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph)’s distance when it is first pushed. Explain the output and the difference with [Listing 25.2](#lst-b1-shortest-paths-dijkstra).

```python
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
```

***Listing 25.6.** Fixed when pushed code/bachelor-1/25-shortest-paths/listings/exo_settle_push.py*

```
{'s': 0, 'a': 5, 'b': 1}
```

***Output 25.7.** [Arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $s \to a$ (5), $s \to b$ (1), $b \to
a$ (1). Some lines are left out.*

**Solution of Exercise 25.5.**

`a` is reached first from `s`, at 5, and fixed; the path $s \to b \to a$, of weight 2, is found later and ignored. Fixing at discovery is right for [breadth-first search](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-bfs), where every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) has the same weight, so the first path found to a [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) has the fewest [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). With weights, a [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) 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 $k$ innermost, 350 entries of the town’s table are wrong. Why?

```python
    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
```

***Listing 25.7.** The loops in another order code/bachelor-1/25-shortest-paths/listings/exo_floyd_inner.py*

```
wrong entries: 350 of 900
```

***Output 25.8.** Against Floyd–Warshall. Some lines are left out.*

**Solution of Exercise 25.6.**

With $k$ innermost, the entry $(i, j)$ is computed once and for all, by trying every single intermediate [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $k$ with the entries $(i, k)$ and $(k, j)$ as they are at that moment, which are not final when $i$ or $j$ comes later in the loops. A path that needs two intermediate [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) whose entries are computed too late is missed. With $k$ outermost, the entries $D_k(i, k)$ and $D_k(k, j)$ are complete for the [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) below $k$ before they are used.

**Exercise 25.7 ★★.**

Compute the smallest weight of a path of at most $k$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) from $s$ to every [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), with any weights, in $O(k(n + m))$, and test it.

**Solution of Exercise 25.7.**

```python
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
```

*Paths of at most $k$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) code/bachelor-1/25-shortest-paths/exercises/at_most_k.py*

By induction, after round $r$, $\texttt{dist}[v]$ is the smallest weight of a path of at most $r$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph): such a path is either of at most $r - 1$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), or a path of at most $r - 1$ [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) to some $u$ followed by $u \to v$. Relaxing from the copy `before` is what keeps one [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) per round; relaxing [in place](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#def-b1-sorting-comparison-sort) could chain several [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) in one round, as Bellman–Ford does on purpose. The test compares with a brute-force enumeration of walks.

**Exercise 25.8 ★★.**

Each [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) has a capacity, for instance the height limit of a road. Find, from $s$, the paths whose smallest capacity is as large as possible, by a variant of Dijkstra’s algorithm, and justify it.

**Solution of Exercise 25.8.**

```python
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
```

*Widest paths code/bachelor-1/25-shortest-paths/exercises/widest.py*

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](#thm-b1-shortest-paths-dijkstra) works with “largest” for “smallest” and $\min$ for $+$: the unsettled [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) of largest width has its final width. The heap holds negated widths, since `heapq` pops the smallest.

**Exercise 25.9 ★★.**

Prove [Proposition 25.3](#prop-b1-shortest-paths-subpath).

**Solution of Exercise 25.9.**

Let $P$ be a [shortest path](#def-b1-shortest-paths-shortest) from $s$ to $v$ and $Q$ its piece from $x$ to $y$. If a path $Q'$ from $x$ to $y$ were lighter, replacing $Q$ by $Q'$ in $P$ would give a walk from $s$ to $v$ lighter than $P$; without [negative cycles](#def-b1-shortest-paths-negative) 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](#def-b1-shortest-paths-shortest) to $u$ followed by $u \to v$ is a walk of weight $\delta(s, u) + w(u, v)$, and $\delta(s, v)$ is at most that (if $\delta(s, u) = +\infty$, there is nothing to prove).

**Exercise 25.10 ★★★.**

Prove [Theorem 25.7](#thm-b1-shortest-paths-dijkstra).

**Solution of Exercise 25.10.**

Estimates are always weights of paths, so $\texttt{dist}[v] \geq \delta(s, v)$. Suppose $u$ is the first [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) settled with $\texttt{dist}[u] > \delta(s, u)$; $u \neq s$, and $u$ is reachable, or its estimate would be $+\infty = \delta(s, u)$. Take a [shortest path](#def-b1-shortest-paths-shortest) from $s$ to $u$; it starts in the settled set and ends outside it. Let $x \to y$ be its first [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) leaving the set. $x$ was settled with $\texttt{dist}[x] = \delta(s, x)$, and relaxed $x \to y$, so $\texttt{dist}[y] \leq
\delta(s, x) + w(x, y) = \delta(s, y) \leq \delta(s, u) < \texttt{dist}[u]$, using [Proposition 25.3](#prop-b1-shortest-paths-subpath) and the non-negative weights after $y$. So $y \neq u$ and $y$ has a smaller key than $u$: it would have been settled first. Contradiction. For the tree: each [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph)’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](#def-b1-shortest-paths-shortest) from $s$ to every [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) in $O(n + m)$, and prove it.

**Solution of Exercise 25.11.**

```python
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
```

*Counting [shortest paths](#def-b1-shortest-paths-shortest) in a DAG code/bachelor-1/25-shortest-paths/exercises/dag_count.py*

By induction along the [topological order](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-topo): when $u$ is taken, every [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) entering $u$ has been relaxed, so $\texttt{dist}[u] = \delta(s, u)$, and `ways[u]` is the sum of `ways[x]` over the [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) $x \to u$ with $\delta(s,
x) + w(x, u) = \delta(s, u)$: each [shortest path](#def-b1-shortest-paths-shortest) to $u$ is a [shortest path](#def-b1-shortest-paths-shortest) to such an $x$ followed by the [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), in exactly one way. When an estimate drops, the count restarts from the new predecessor’s. Each [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) is handled once: $O(n + m)$, with zero weights allowed, since there is no cycle.

**Exercise 25.12 ★★★.**

Write a function that returns a [negative cycle](#def-b1-shortest-paths-negative) of a [graph](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), as a list of [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), or `None`, in $O(nm)$.

**Solution of Exercise 25.12.**

```python
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]
```

*A [negative cycle](#def-b1-shortest-paths-negative) code/bachelor-1/25-shortest-paths/exercises/negative_cycle.py*

Starting every estimate at 0 is Bellman–Ford from a new [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) joined to all others by [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) of weight 0, so every cycle is reachable. If round $n$ still lowers the estimate of some [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), the parent links contain a cycle: following them back $n$ steps from that [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) cannot avoid repeating a [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). 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 $n$ rounds of $O(m)$.

## 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](#lst-b1-shortest-paths-wgraph).

```python
def eccentricities(order, d):
    return {v: max(d[i]) for i, v in enumerate(order)}
```

***Listing 25.8.** Eccentricities from the distance table code/bachelor-1/25-shortest-paths/listings/centre.py*

```
$ 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
```

***Output 25.9.** The three most central places, the two least central, the [centre](#def-b1-shortest-paths-centre) and the [diameter](#def-b1-shortest-paths-centre).*

**Part I — Modelling.**

1. Compute the travel time of a road of 1360 m at 50 km/h, as the program does.
2. Why does the Station have an [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) of 120 s to the Town Hall but only 35 s to River Park?
3. How many [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) does the town have, and why not 106?
4. Why are the weights in whole seconds, and what does rounding cost on a route of seven roads?
5. Why must a one-way road be an [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) , not an edge, in this model?
6. Could the weights be negative here? Which algorithms would still apply?

**Part II — Dijkstra from the Town Square.**

7. Read the fastest and the shortest routes to the Hospital, and compare their lengths and times.
8. Why did the search pop 35 entries for 30 places?
9. Bound the number of pops in terms of $n$ and $m$ .
10. Why do the parents form a tree, and why is it a [shortest-path tree](#def-b1-shortest-paths-tree) ?
11. Up to which place do the two routes agree, and what does [Proposition 25.3](#prop-b1-shortest-paths-subpath) say of their first parts?
12. [Breadth-first search](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-bfs) found a route of six roads to the Hospital in [Output 24.5](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#out-b1-graph-traversals-bfs) : compare it with the two routes.

**Part III — All pairs.**

13. Prove by induction on $k$ that $D_k(i, j)$ , as defined by the recurrence, is the smallest weight of a path from $i$ to $j$ with all intermediate [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) less than $k$ .
14. Deduce that $D_n$ is the distance table.
15. Show that the in-place update computes the same table.
16. Explain how `nxt` rebuilds a route, and why `nxt[i][j] = nxt[i][k]` is right.
17. Why do the Library and the Town Square have different distances in the two directions?
18. Compare the costs of Floyd–Warshall and of 30 runs of Dijkstra on the town.

**Part IV — The centre.**

19. Explain `max(d[i])` : why is the distance from a place to itself harmless?
20. Read the [centre](#def-b1-shortest-paths-centre) , the radius and the [diameter](#def-b1-shortest-paths-centre) .
21. Why does the Post Office appear as farthest for several places?
22. Show that the [diameter](#def-b1-shortest-paths-centre) is at most twice the radius when every road is two-way.
23. Does that bound hold for Brenmoor, with its one-way road?
24. State the named result, *the town’s [centre](#def-b1-shortest-paths-centre) and [diameter](#def-b1-shortest-paths-centre)* , with its proof.

**Solution of Problem 25.1.**

**1.** $1360 \times 3.6 / 50 = 97.92$, 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) 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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) had been pushed.

**9.** One push for the source and at most one per relaxed [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph), so at most $m + 1$ pushes and pops: 106 here.

**10.** The parent of $v$ was settled before $v$, so following parents goes back in the order of settling and ends at $s$: no cycle, a tree. By [Theorem 25.7](#thm-b1-shortest-paths-dijkstra), its paths are shortest.

**11.** Up to River Park, by the North [Bridge](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-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 $k = 0$, a path without intermediate [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) is the empty path or a single [arc](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph). A best path from $i$ to $j$ with intermediate [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) less than $k + 1$ avoids $k$, and weighs $D_k(i, j)$, or passes through $k$ once (without [negative cycles](#def-b1-shortest-paths-negative) it need not pass twice), and splits into two paths with intermediate [vertices](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) less than $k$, each best by cut and paste: $D_k(i, k) + D_k(k, j)$.

**14.** With $k = n$, every [vertex](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) may be intermediate: $D_n(i, j) = \delta(i, j)$.

**15.** In round $k$, the entries $D(i, k)$ and $D(k, j)$ do not change, since $D_k(k, k) = 0$ without [negative cycles](#def-b1-shortest-paths-negative). So every entry read in round $k$ has its value of $D_k$, whether it was updated already or not.

**16.** `nxt[i][j]` is the first step of a best path from $i$ to $j$; the route follows it until $j$. When the path through $k$ wins, its first step is the first step of the best path from $i$ to $k$.

**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](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) and [arcs](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#def-b1-graph-traversals-graph) with heap operations of about 7 comparisons: about 30 runs $\times$ 1000, of the same order. Floyd–Warshall’s loop is simpler; Dijkstra’s runs would win on a larger town, since $n^3$ grows faster than $n^2 \log n$.

**19.** `max(d[i])` is the largest distance from place $i$; the 0 of $d[i][i]$ never wins when there are other places, all at positive distance.

**20.** The [centre](#def-b1-shortest-paths-centre) is the Town Hall, with radius 349 s (5.8 min); the [diameter](#def-b1-shortest-paths-centre) 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 $u$ and $v$ and the [centre](#def-b1-shortest-paths-centre) $c$: $\delta(u, v) \leq \delta(u, c) +
\delta(c, v) = \delta(c, u) + \delta(c, v) \leq 2r$.

**23.** The proof uses $\delta(u, c) = \delta(c, u)$, which the one-way road can break; the bound still holds here, $675 \leq 698$, but it is checked, not proved.

**24.** *The town’s [centre](#def-b1-shortest-paths-centre) and [diameter](#def-b1-shortest-paths-centre)*: 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](#def-b1-shortest-paths-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.
