Relaxation and Its Properties
Bellman-Ford, the DAG algorithm and Dijkstra look different, but they share one inner operation and differ only in the order in which they apply it. That operation is relaxation: given an edge , ask whether going through gives a better route to than the best one known so far, and if so, take it. This lesson defines relaxation and proves five properties of it. Every correctness proof in the rest of this section is a short combination of them.
Estimates and the relax step
Each vertex keeps a shortest-path estimate , an upper bound on that only ever decreases, and a predecessor .
INITIALIZE-SINGLE-SOURCE(G, s)
1 for each vertex v in G.V
2 v.d = infinity; v.pi = NIL
3 s.d = 0
RELAX(u, v, w)
1 if v.d > u.d + w(u, v)
2 v.d = u.d + w(u, v)
3 v.pi = uRelaxing an edge costs . The name comes from the image of a spring: the estimate is held too high, and relaxing the edge lets it move toward its natural length. The algorithms are:
| Algorithm | Which edges are relaxed, in what order | Relaxations |
|---|---|---|
| Bellman-Ford | every edge, times over | |
| DAG shortest paths | each vertex's outgoing edges, in topological order | |
| Dijkstra | each vertex's outgoing edges, in order of final distance |
The program relaxes the edges of a small graph one at a time and prints every change.
INF = float("inf")
edges = [("A", "B", 6), ("A", "C", 2), ("C", "B", 3), ("B", "D", -2), ("C", "D", 7), ("D", "E", 1), ("C", "E", 8)]
d = {v: INF for v in "ABCDE"}
pi = {v: None for v in "ABCDE"}
d["A"] = 0
def relax(u, v, w):
if d[v] > d[u] + w:
print(f"relax {u}->{v}: {d[v]} > {d[u]} + {w}, so d[{v}] = {d[u] + w}, pi[{v}] = {u}")
d[v], pi[v] = d[u] + w, u
return True
print(f"relax {u}->{v}: d[{v}] = {d[v]} <= {d[u]} + {w}, no change")
return False
for u, v, w in [edges[4], edges[1], edges[4], edges[0], edges[2], edges[3], edges[5]]:
relax(u, v, w)
print("estimates:", d)relax C->D: d[D] = inf <= inf + 7, no change
relax A->C: inf > 0 + 2, so d[C] = 2, pi[C] = A
relax C->D: inf > 2 + 7, so d[D] = 9, pi[D] = C
relax A->B: inf > 0 + 6, so d[B] = 6, pi[B] = A
relax C->B: 6 > 2 + 3, so d[B] = 5, pi[B] = C
relax B->D: 9 > 5 + -2, so d[D] = 3, pi[D] = B
relax D->E: inf > 3 + 1, so d[E] = 4, pi[E] = D
estimates: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
The first relaxation of does nothing because is still . After it lowers to 9, a valid but poor estimate, which later improves to the true distance 3. Whether the estimates end up exact depends on the order, and that is what the properties below control.
Five properties
Assume has no negative cycle reachable from and that the estimates were set by INITIALIZE-SINGLE-SOURCE and then changed only by RELAX. (Properties 1 and 2 need neither assumption.)
1. Triangle inequality. For every edge , . A shortest path to followed by is a path to , and is at most its weight. (If the inequality is trivial.)
2. Upper-bound property. At all times , and once it never changes. Induction on relaxations. Initially it holds. When RELAX sets , we have by induction and the triangle inequality. Estimates only decrease, so one that reaches its lower bound stays there.
3. No-path property. If is unreachable from , then forever. This is the upper-bound property with .
4. Convergence property. If is a shortest path to and at some time before is relaxed, then at all times afterwards. After the relaxation, , the last step by optimal substructure. With the upper-bound property, , and it stays.
5. Path-relaxation property. If is a shortest path from to , and the edges are relaxed in this order, then afterwards. This holds no matter what other relaxations are mixed in between. Induction on : after is relaxed, . For , (no negative cycle means ). The step is the convergence property, and the upper-bound property says other relaxations cannot undo it.
There is a sixth fact, the predecessor-subgraph property: once all estimates equal the distances, the edges form a shortest-path tree rooted at . Its proof is longer (it shows that the predecessor graph never contains a cycle while no negative cycle is reachable) and is omitted here.
Testing the properties
The program applies thousands of random relaxations to random graphs with negative edges but no negative cycles (the weights come from a potential, explained in Johnson's algorithm, which guarantees that). After every relaxation it checks the upper-bound property. For the path-relaxation property, it hides the edges of one shortest path, in order, inside a random sequence of other relaxations and checks that the end vertex is exact.
import random
INF = float("inf")
def random_graph(rng, n):
h = [rng.randint(-10, 10) for _ in range(n)] # a potential
edges = []
for u in range(n):
for v in range(n):
if u != v and rng.random() < 0.3:
edges.append((u, v, rng.randint(0, 9) + h[u] - h[v])) # every cycle weighs >= 0
return edges
def exact(n, edges, s):
d = [INF] * n; d[s] = 0
for _ in range(n - 1):
for u, v, w in edges:
if d[u] + w < d[v]:
d[v] = d[u] + w
return d
def shortest_path_to(n, edges, s, t, delta):
# walk back from t along edges that are tight: delta[u] + w == delta[v]
path, v = [t], t
while v != s:
u, w = next((u, w) for u, x, w in edges if x == v and delta[u] + w == delta[v] and delta[u] < INF and u not in path)
path.append(u); v = u
return path[::-1]
rng = random.Random(42)
checks = paths = 0
for trial in range(200):
n = rng.randint(2, 9)
edges = random_graph(rng, n)
if not edges:
continue
delta = exact(n, edges, 0)
d = [INF] * n; d[0] = 0
for _ in range(30):
u, v, w = rng.choice(edges)
if d[u] + w < d[v]:
d[v] = d[u] + w
assert all(d[x] >= delta[x] for x in range(n)) # upper-bound property
checks += 1
reachable = [t for t in range(1, n) if delta[t] < INF]
if reachable:
t = rng.choice(reachable)
p = shortest_path_to(n, edges, 0, t, delta)
path_edges = [next(e for e in edges if e[0] == a and e[1] == b) for a, b in zip(p, p[1:])]
seq = []
for e in path_edges: # the path's edges, in order, among noise
seq += [rng.choice(edges) for _ in range(rng.randint(0, 5))] + [e]
d = [INF] * n; d[0] = 0
for u, v, w in seq:
if d[u] + w < d[v]:
d[v] = d[u] + w
assert d[t] == delta[t] # path-relaxation property
paths += 1
print(f"upper-bound property held after {checks} random relaxations")
print(f"path-relaxation property held for {paths} hidden shortest paths")upper-bound property held after 5580 random relaxations
path-relaxation property held for 141 hidden shortest paths
Order matters
The path-relaxation property says what a good order looks like: the edges of every shortest path relaxed front to back. If the edges of a path are relaxed back to front, each sweep over them makes progress of only one edge. The program relaxes all edges of a path of 8 vertices repeatedly, once in forward order and once in reverse, and counts the sweeps until nothing changes.
INF = float("inf")
n = 8
path = [(i, i + 1, 1) for i in range(n - 1)]
def sweeps(order):
d = [INF] * n; d[0] = 0
count = 0
while True:
count += 1
changed = False
for u, v, w in order:
if d[u] + w < d[v]:
d[v] = d[u] + w; changed = True
if not changed:
return count, d
print("forward order:", sweeps(path))
print("reverse order:", sweeps(path[::-1]))forward order: (2, [0, 1, 2, 3, 4, 5, 6, 7])
reverse order: (8, [0, 1, 2, 3, 4, 5, 6, 7])
Forward order gets every distance right in the first sweep (the second sweep only confirms that nothing changes). Reverse order needs sweeps plus the confirming one. Bellman-Ford does not know a good order, so it pays for the worst case with sweeps; the DAG algorithm and Dijkstra find a good order and relax each edge once.
In C++
The C++ version is the generic "relax until nothing changes" loop, which is Bellman-Ford without the bound. It prints the final estimates and parents of the lesson's first graph.
#include <climits>
#include <cstdio>
#include <vector>
struct Edge { int u, v, w; };
int main() {
const int n = 5; // A..E
std::vector<Edge> edges = {{0,1,6}, {0,2,2}, {2,1,3}, {1,3,-2}, {2,3,7}, {3,4,1}, {2,4,8}};
const long long INF = LLONG_MAX / 4;
std::vector<long long> d(n, INF);
std::vector<int> pi(n, -1);
d[0] = 0;
auto relax = [&](const Edge& e) {
if (d[e.u] < INF && d[e.v] > d[e.u] + e.w) { d[e.v] = d[e.u] + e.w; pi[e.v] = e.u; return true; }
return false;
};
int sweeps = 0, relaxations = 0;
bool changed = true;
while (changed) {
changed = false;
++sweeps;
for (const auto& e : edges) if (relax(e)) { changed = true; ++relaxations; }
}
for (int v = 0; v < n; ++v)
std::printf("%c: d = %lld, parent %c\n", 'A' + v, d[v], pi[v] < 0 ? '-' : 'A' + pi[v]);
std::printf("%d sweeps, %d successful relaxations\n", sweeps, relaxations);
}A: d = 0, parent -
B: d = 5, parent C
C: d = 2, parent A
D: d = 3, parent B
E: d = 4, parent D
2 sweeps, 5 successful relaxations
Test yourself
What does RELAX do when ?
- Sets
- Nothing
- Sets only
- Reports a negative cycle
Which property guarantees that an estimate, once correct, is never spoiled by later relaxations?
- Triangle inequality
- Upper-bound property
- No-path property
- Convergence property
A shortest path exists. Which relaxation sequence is guaranteed to make exact (with arbitrary other relaxations in between)?
- Any sequence containing all three edges