TExcelTAD
Home › Graph Algorithms › Relaxation and Its Properties

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 (u,v)(u, v), ask whether going through uu gives a better route to vv 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 vv keeps a shortest-path estimate v.dv.d, an upper bound on δ(s,v)\delta(s, v) that only ever decreases, and a predecessor v.πv.\pi.

text
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 = u

Relaxing an edge costs O(1)O(1). The name comes from the image of a spring: the estimate v.dv.d 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, V−1V - 1 times over Θ(VE)\Theta(VE)
DAG shortest paths each vertex's outgoing edges, in topological order Θ(E)\Theta(E)
Dijkstra each vertex's outgoing edges, in order of final distance Θ(E)\Theta(E)

The program relaxes the edges of a small graph one at a time and prints every change.

python · try it yourself
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 C→DC \to D does nothing because C.dC.d is still ∞\infty. After A→CA \to C it lowers D.dD.d to 9, a valid but poor estimate, which B→DB \to D 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 GG has no negative cycle reachable from ss 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 (u,v)(u, v), δ(s,v)≤δ(s,u)+w(u,v)\delta(s, v) \le \delta(s, u) + w(u, v). A shortest path to uu followed by (u,v)(u, v) is a path to vv, and δ(s,v)\delta(s, v) is at most its weight. (If δ(s,u)=∞\delta(s, u) = \infty the inequality is trivial.)

2. Upper-bound property. At all times v.d≥δ(s,v)v.d \ge \delta(s, v), and once v.d=δ(s,v)v.d = \delta(s, v) it never changes. Induction on relaxations. Initially it holds. When RELAX sets v.d=u.d+w(u,v)v.d = u.d + w(u, v), we have u.d+w(u,v)≥δ(s,u)+w(u,v)≥δ(s,v)u.d + w(u, v) \ge \delta(s, u) + w(u, v) \ge \delta(s, v) by induction and the triangle inequality. Estimates only decrease, so one that reaches its lower bound stays there.

3. No-path property. If vv is unreachable from ss, then v.d=∞v.d = \infty forever. This is the upper-bound property with δ(s,v)=∞\delta(s, v) = \infty.

4. Convergence property. If s⇝u→vs \leadsto u \to v is a shortest path to vv and u.d=δ(s,u)u.d = \delta(s, u) at some time before (u,v)(u, v) is relaxed, then v.d=δ(s,v)v.d = \delta(s, v) at all times afterwards. After the relaxation, v.d≤u.d+w(u,v)=δ(s,u)+w(u,v)=δ(s,v)v.d \le u.d + w(u, v) = \delta(s, u) + w(u, v) = \delta(s, v), the last step by optimal substructure. With the upper-bound property, v.d=δ(s,v)v.d = \delta(s, v), and it stays.

5. Path-relaxation property. If p=⟨v0,v1,…,vk⟩p = \langle v_0, v_1, \ldots, v_k \rangle is a shortest path from s=v0s = v_0 to vkv_k, and the edges (v0,v1),(v1,v2),…,(vk−1,vk)(v_0, v_1), (v_1, v_2), \ldots, (v_{k-1}, v_k) are relaxed in this order, then vk.d=δ(s,vk)v_k.d = \delta(s, v_k) afterwards. This holds no matter what other relaxations are mixed in between. Induction on ii: after (vi−1,vi)(v_{i-1}, v_i) is relaxed, vi.d=δ(s,vi)v_i.d = \delta(s, v_i). For i=0i = 0, s.d=0=δ(s,s)s.d = 0 = \delta(s, s) (no negative cycle means δ(s,s)=0\delta(s, s) = 0). 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 (v.π,v)(v.\pi, v) form a shortest-path tree rooted at ss. 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.

python · try it yourself
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.

python · try it yourself
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 V−1=7V - 1 = 7 sweeps plus the confirming one. Bellman-Ford does not know a good order, so it pays for the worst case with V−1V - 1 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 V−1V - 1 bound. It prints the final estimates and parents of the lesson's first graph.

cpp · try it yourself
#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(u,v,w)(u, v, w) do when v.d≤u.d+w(u,v)v.d \le u.d + w(u, v)?

  1. Sets v.d=u.d+w(u,v)v.d = u.d + w(u, v)
  2. Nothing
  3. Sets v.π=uv.\pi = u only
  4. Reports a negative cycle

Which property guarantees that an estimate, once correct, is never spoiled by later relaxations?

  1. Triangle inequality
  2. Upper-bound property
  3. No-path property
  4. Convergence property

A shortest path s→a→b→ts \to a \to b \to t exists. Which relaxation sequence is guaranteed to make t.dt.d exact (with arbitrary other relaxations in between)?

  1. (b,t),(a,b),(s,a)(b, t), (a, b), (s, a)
  2. (s,a),(b,t),(a,b)(s, a), (b, t), (a, b)
  3. (s,a),(a,b),(b,t)(s, a), (a, b), (b, t)
  4. Any sequence containing all three edges