Shortest Paths, Negative Edges and Cycles
Breadth-first search finds paths with the fewest edges. Most route-finding problems care about something else: the total length in kilometres, the travel time, the price of the tickets, the probability of failure along the way. Each edge then carries a weight, and the best path is the one of least total weight. This section of the course solves the single-source version: from one source , find a lightest path to every vertex. This first lesson sets up the definitions, explains why negative weights are allowed but negative cycles are not, and proves the structural fact every shortest-path algorithm relies on. The DSA course has a gentler introduction.
Definitions and variants
Let be a directed graph with weights . The weight of a path is
and the shortest-path weight from to is
A shortest path from to is any path with . Undirected graphs are handled by replacing each edge with two arcs of the same weight (as long as weights are non-negative; a negative undirected edge is a negative cycle of length two).
| Variant | Question | Solved by |
|---|---|---|
| single-source | for one and every | this section |
| single-destination | for every | single-source on the reversed graph |
| single-pair | for one pair | no known algorithm is asymptotically faster than single-source in the worst case |
| all-pairs | for every pair | the next section, or single-source from every vertex |
Optimal substructure
Lemma (subpaths of shortest paths are shortest paths). If is a shortest path from to , then for all the subpath is a shortest path from to .
Cut and paste: split into , and . If some path from to were lighter than , then , , would be a path from to lighter than . This is the optimal-substructure argument of dynamic programming, and every algorithm in this section is, at heart, a way of filling in the table in a valid order.
Negative weights and negative cycles
Negative edge weights make sense: a refund on a leg of a journey, an energy gain on a downhill stretch, a profit in a currency exchange. They are fine as long as no cycle reachable from has negative total weight. If one does, going around it again and again makes the path weight as small as we like, so for every that can be reached from the cycle. The program shows both situations. It computes, for , the lightest weight of a walk (a path that may repeat vertices) with at most edges from . In the first graph the values settle; in the second, which adds the cycle of weight , they keep falling.
INF = float("inf")
def lightest_walks(V, edges, s, kmax):
d = {v: INF for v in V}
d[s] = 0
history = []
for k in range(1, kmax + 1):
nd = dict(d)
for u, v, w in edges:
if d[u] + w < nd[v]:
nd[v] = d[u] + w
d = nd
history.append(dict(d))
return history
base = [("A", "B", 6), ("A", "C", 2), ("C", "B", 3), ("B", "D", -2), ("C", "D", 7), ("D", "E", 1), ("C", "E", 8)]
print("no negative cycle:")
for k, d in enumerate(lightest_walks("ABCDE", base, "A", 6), 1):
print(f" k = {k}:", d)
cyc = base + [("B", "F", 2), ("F", "G", -4), ("G", "B", 1)]
print("with the cycle B -> F -> G -> B of weight -1:")
for k, d in enumerate(lightest_walks("ABCDEFG", cyc, "A", 12), 1):
if k % 3 == 0:
print(f" k = {k:2}: B = {d['B']}, D = {d['D']}, E = {d['E']}")no negative cycle:
k = 1: {'A': 0, 'B': 6, 'C': 2, 'D': inf, 'E': inf}
k = 2: {'A': 0, 'B': 5, 'C': 2, 'D': 4, 'E': 10}
k = 3: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 5}
k = 4: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
k = 5: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
k = 6: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
with the cycle B -> F -> G -> B of weight -1:
k = 3: B = 5, D = 3, E = 5
k = 6: B = 4, D = 2, E = 4
k = 9: B = 3, D = 1, E = 3
k = 12: B = 2, D = 0, E = 2
Without the cycle the values stop changing after 4 edges, because a shortest path never needs more than edges (below). With the cycle, every lap lowers , and by one more: their shortest-path weight is , while and , which cannot be reached from the cycle, still have finite values. Bellman-Ford detects exactly this situation.
Shortest paths can be taken simple
If no negative cycle is reachable, a shortest path never needs a cycle. A cycle of positive weight can be cut out to make the path lighter; a cycle of weight zero can be cut out without changing the weight. So whenever is finite, some simple shortest path exists, and a simple path has at most edges. That bound is why Bellman-Ford runs rounds.
The program checks it by brute force: it lists every simple path from in the first graph and compares the lightest with the walk values above.
base = [("A", "B", 6), ("A", "C", 2), ("C", "B", 3), ("B", "D", -2), ("C", "D", 7), ("D", "E", 1), ("C", "E", 8)]
adj = {}
for u, v, w in base:
adj.setdefault(u, []).append((v, w))
best = {}
def walk(u, path, weight):
if u not in best or weight < best[u][0]:
best[u] = (weight, path)
for v, w in adj.get(u, []):
if v not in path:
walk(v, path + [v], weight + w)
walk("A", ["A"], 0)
for v in sorted(best):
weight, path = best[v]
print(f"delta(A, {v}) = {weight:2} via {' -> '.join(path)}, edges: {len(path) - 1}")delta(A, A) = 0 via A, edges: 0
delta(A, B) = 5 via A -> C -> B, edges: 2
delta(A, C) = 2 via A -> C, edges: 1
delta(A, D) = 3 via A -> C -> B -> D, edges: 3
delta(A, E) = 4 via A -> C -> B -> D -> E, edges: 4
Shortest-path trees
Like BFS, the algorithms of this section store a predecessor for every vertex instead of whole paths. When they finish, the edges form a shortest-path tree rooted at : a tree containing every vertex reachable from , in which the tree path from to is a shortest path in . It exists because of optimal substructure: if , a shortest path to followed by is a shortest path to . Shortest paths and shortest-path trees need not be unique; two paths of equal weight may both qualify.
The animation is a preview of the next lessons: Bellman-Ford on the first graph, relaxing the edges in the order listed, until the labels equal the distances printed above.
Test yourself
A graph has a cycle of total weight that is reachable from , and is reachable from the cycle. What is ?
- The weight of the lightest simple path
Why does a shortest path in a graph without negative cycles never need more than edges?
- Because weights are positive
- Because any cycle in it has non-negative weight and can be removed, leaving a simple path, which has at most edges
- Because BFS says so
- Because
Which property lets shortest-path algorithms store only one predecessor per vertex?
- Negative weights
- Subpaths of shortest paths are shortest paths
- The graph is a DAG
- Edge weights are distinct