TExcelTAD
Home › Approximation Algorithms › Christofides' Algorithm

Christofides' Algorithm

The double-tree algorithm makes the spanning tree Eulerian by doubling every edge. But only the vertices of odd degree need fixing, and pairing them up with a cheap matching costs at most half a tour. That observation, made by Christofides (1976) and independently by Serdyukov (1978), gives a 32\frac{3}{2}-approximation for metric TSP, a bound that stood unbeaten for more than four decades.

The algorithm

text
CHRISTOFIDES(G, c)                          -- c metric
1  T = a minimum spanning tree
2  O = the vertices of odd degree in T
3  M = a minimum-cost perfect matching on O  (in the complete graph on O)
4  H = T + M                                 -- a multigraph, all degrees even
5  W = an Euler circuit of H
6  return the tour obtained by shortcutting W

∣O∣\lvert O \rvert is even by the handshake lemma (the degrees of TT sum to 2(n−1)2(n - 1), so the number of odd ones is even), hence a perfect matching on OO exists. Adding one matching edge at each odd vertex makes every degree of HH even, and HH is connected because it contains TT. A minimum-cost perfect matching in a general graph takes polynomial time with Edmonds' blossom algorithm (1965), O(n3)O(n^3) in good implementations; the programs below use a bitmask dynamic program instead, which is exponential in ∣O∣\lvert O \rvert but short and fine for small instances.

The analysis

Theorem (Christofides, 1976). For metric costs, the algorithm returns a tour of cost at most 32 OPT\frac{3}{2}\,\text{OPT}.

Proof. As before, c(T)≤OPTc(T) \le \text{OPT}. For the matching, take an optimal tour H∗H^* and shortcut it to the vertices of OO only: by the triangle inequality the resulting cycle COC_O costs at most OPT\text{OPT}. COC_O has an even number of vertices, so its edges alternate between two perfect matchings M1M_1 and M2M_2 on OO with c(M1)+c(M2)=c(CO)≤OPTc(M_1) + c(M_2) = c(C_O) \le \text{OPT}. The cheaper one costs at most 12OPT\frac{1}{2}\text{OPT}, and the minimum matching MM is no more expensive. So

ALG≤c(W)=c(T)+c(M)≤OPT+12 OPT=32 OPT.□\text{ALG} \le c(W) = c(T) + c(M) \le \text{OPT} + \tfrac{1}{2}\,\text{OPT} = \tfrac{3}{2}\,\text{OPT}. \qquad \square

Two lower bounds are combined: the MST (a tour minus an edge) and half a tour on OO (two matchings). Neither is new; the improvement over 2 comes from paying for only the parity defect of the tree.

python · try it yourself
import random
from math import dist, inf
from functools import lru_cache

def prim(pts):
    n = len(pts)
    best, parent, done, adj = [inf] * n, [-1] * n, [False] * n, {v: [] for v in range(n)}
    best[0] = 0
    for _ in range(n):
        u = min((i for i in range(n) if not done[i]), key=lambda i: best[i])
        done[u] = True
        if parent[u] >= 0:
            adj[u].append(parent[u]); adj[parent[u]].append(u)
        for v in range(n):
            if not done[v] and dist(pts[u], pts[v]) < best[v]:
                best[v], parent[v] = dist(pts[u], pts[v]), u
    return adj

def min_matching(pts, odd):
    @lru_cache(None)
    def go(mask):                          # mask = odd vertices still unmatched
        if not mask:
            return 0.0, ()
        i = (mask & -mask).bit_length() - 1
        best = (inf, ())
        for j in range(i + 1, len(odd)):
            if mask >> j & 1:
                c, m = go(mask & ~(1 << i) & ~(1 << j))
                c += dist(pts[odd[i]], pts[odd[j]])
                if c < best[0]:
                    best = (c, m + ((odd[i], odd[j]),))
        return best
    return go((1 << len(odd)) - 1)

def euler_then_shortcut(n, adj):
    adj = {v: list(a) for v, a in adj.items()}
    stack, walk = [0], []
    while stack:
        u = stack[-1]
        if adj[u]:
            v = adj[u].pop()
            adj[v].remove(u)
            stack.append(v)
        else:
            walk.append(stack.pop())
    seen = []
    for v in walk:
        if v not in seen:
            seen.append(v)
    return seen

def christofides(pts):
    adj = prim(pts)
    mst = sum(dist(pts[u], pts[v]) for u in adj for v in adj[u]) / 2
    odd = [v for v in adj if len(adj[v]) % 2]
    cM, M = min_matching(pts, odd)
    for u, v in M:
        adj[u].append(v); adj[v].append(u)
    tour = euler_then_shortcut(len(pts), adj)
    return mst, len(odd), cM, sum(dist(pts[tour[i]], pts[tour[i - 1]]) for i in range(len(tour)))

def held_karp(pts):
    n = len(pts)
    D = [[inf] * n for _ in range(1 << n)]
    D[1][0] = 0.0
    for S in range(1, 1 << n, 2):
        for j in range(n):
            if D[S][j] < inf:
                for k in range(1, n):
                    if not S >> k & 1:
                        D[S | 1 << k][k] = min(D[S | 1 << k][k], D[S][j] + dist(pts[j], pts[k]))
    return min(D[-1][j] + dist(pts[j], pts[0]) for j in range(1, n))

rng = random.Random(21)
print(" n    MST  |O|  matching   tour    OPT  ratio")
for n in [7, 8, 9, 10]:
    pts = [(rng.randint(0, 100), rng.randint(0, 100)) for _ in range(n)]
    mst, k, cM, tour = christofides(pts)
    opt = held_karp(pts)
    print(f"{n:2} {mst:6.1f} {k:4} {cM:9.1f} {tour:6.1f} {opt:6.1f} {tour / opt:6.3f}")
 n    MST  |O|  matching   tour    OPT  ratio
 7  119.0    2      47.7  166.7  166.7  1.000
 8  246.9    4     142.1  350.0  350.0  1.000
 9  190.9    4      96.4  287.2  270.5  1.062
10  267.5    6     173.5  430.5  363.6  1.184

In every row the matching costs at most half of OPT, and the tour at most MST plus matching.

In C++

The same pipeline on a fixed point set: Prim, odd-degree vertices, bitmask matching, Hierholzer, shortcut.

cpp · try it yourself
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>

std::vector<std::pair<double, double>> P = {{0, 0}, {40, 10}, {80, 0}, {95, 45}, {70, 80}, {30, 75}, {5, 50}, {50, 45}};
double d(int a, int b) { return std::hypot(P[a].first - P[b].first, P[a].second - P[b].second); }

int main() {
    int n = P.size();
    std::vector<std::vector<int>> adj(n);
    std::vector<double> best(n, 1e18);
    std::vector<int> parent(n, -1);
    std::vector<bool> done(n, false);
    best[0] = 0;
    double mst = 0;
    for (int it = 0; it < n; it++) {
        int u = -1;
        for (int v = 0; v < n; v++) if (!done[v] && (u < 0 || best[v] < best[u])) u = v;
        done[u] = true;
        if (parent[u] >= 0) { adj[u].push_back(parent[u]); adj[parent[u]].push_back(u); mst += d(u, parent[u]); }
        for (int v = 0; v < n; v++) if (!done[v] && d(u, v) < best[v]) { best[v] = d(u, v); parent[v] = u; }
    }
    std::vector<int> odd;
    for (int v = 0; v < n; v++) if (adj[v].size() % 2) odd.push_back(v);
    int k = odd.size(), full = (1 << k) - 1;
    std::vector<double> f(1 << k, 1e18);                 // f[mask] = cheapest matching of the vertices in mask
    std::vector<int> pick(1 << k, -1);
    f[0] = 0;
    for (int mask = 1; mask <= full; mask++) {
        if (__builtin_popcount(mask) % 2) continue;
        int i = __builtin_ctz(mask);
        for (int j = i + 1; j < k; j++)
            if (mask >> j & 1) {
                double c = f[mask ^ (1 << i) ^ (1 << j)] + d(odd[i], odd[j]);
                if (c < f[mask]) { f[mask] = c; pick[mask] = j; }
            }
    }
    for (int mask = full; mask; ) {
        int i = __builtin_ctz(mask), j = pick[mask];
        adj[odd[i]].push_back(odd[j]); adj[odd[j]].push_back(odd[i]);
        mask ^= (1 << i) | (1 << j);
    }
    std::vector<int> stack = {0}, walk;
    while (!stack.empty()) {
        int u = stack.back();
        if (!adj[u].empty()) {
            int v = adj[u].back(); adj[u].pop_back();
            adj[v].erase(std::find(adj[v].begin(), adj[v].end(), u));
            stack.push_back(v);
        } else { walk.push_back(u); stack.pop_back(); }
    }
    std::vector<int> tour;
    std::vector<bool> seen(n, false);
    for (int v : walk) if (!seen[v]) { seen[v] = true; tour.push_back(v); }
    double len = 0;
    for (int i = 0; i < n; i++) len += d(tour[i], tour[(i + 1) % n]);
    std::printf("MST %.1f, %d odd vertices, matching %.1f\ntour:", mst, k, f[full]);
    for (int v : tour) std::printf(" %d", v);
    std::printf(", length %.1f <= %.1f\n", len, mst + f[full]);
}
MST 273.6, 6 odd vertices, matching 133.9
tour: 0 1 7 5 6 4 3 2, length 391.1 <= 407.5

The factor 3/2 is tight for the algorithm

Take a strip of triangles: bottom vertices a0,…,aka_0, \ldots, a_k, top vertices b0,…,bk−1b_0, \ldots, b_{k-1}, zigzag edges aibia_i b_i and biai+1b_i a_{i+1} of cost 1, horizontal edges aiai+1a_i a_{i+1} and bibi+1b_i b_{i+1} of cost 1+δ1 + \delta, and all other costs given by shortest paths (so they are metric). The unique MST is the zigzag path, of cost 2k2k; its only odd vertices are the ends a0a_0 and aka_k, matched at cost k(1+δ)k(1 + \delta) along the bottom. The tree plus the matching edge is already a cycle, so Christofides returns about 3k3k. Going along the bottom, up, and back along the top costs (2k−1)(1+δ)+2≈2k(2k - 1)(1 + \delta) + 2 \approx 2k.

python · try it yourself
from math import inf

def strip(k, delta):
    a = lambda i: i                 # bottom vertices 0..k
    b = lambda i: k + 1 + i         # top vertices k+1..2k
    n = 2 * k + 1
    c = [[0 if u == v else inf for v in range(n)] for u in range(n)]
    def edge(u, v, w):
        c[u][v] = c[v][u] = w
    for i in range(k):
        edge(a(i), b(i), 1); edge(b(i), a(i + 1), 1); edge(a(i), a(i + 1), 1 + delta)
        if i + 1 < k:
            edge(b(i), b(i + 1), 1 + delta)
    for m in range(n):              # Floyd-Warshall: metric closure
        for u in range(n):
            for v in range(n):
                c[u][v] = min(c[u][v], c[u][m] + c[m][v])
    return c, a, b

for k in [2, 4, 8, 16, 32]:
    delta = 0.01
    c, a, b = strip(k, delta)
    christofides = 2 * k + c[a(0)][a(k)]          # zigzag MST + matching edge a_0 a_k
    tour = [a(i) for i in range(k + 1)] + [b(i) for i in reversed(range(k))]
    good = sum(c[tour[i]][tour[i - 1]] for i in range(len(tour)))
    print(f"k = {k:2}: Christofides {christofides:6.2f}, a tour of cost {good:6.2f}, ratio at least {christofides / good:.3f}")
k =  2: Christofides   6.02, a tour of cost   5.03, ratio at least 1.197
k =  4: Christofides  12.04, a tour of cost   9.07, ratio at least 1.327
k =  8: Christofides  24.08, a tour of cost  17.15, ratio at least 1.404
k = 16: Christofides  48.16, a tour of cost  33.31, ratio at least 1.446
k = 32: Christofides  96.32, a tour of cost  65.63, ratio at least 1.468

Common mistakes

  • Matching the wrong vertices or with the wrong matching. The matching must be a minimum-cost perfect matching on the odd-degree vertices, in the complete graph on them. A greedy matching (repeatedly join the closest pair) is easy to code but can cost far more than the minimum (Reingold and Tarjan, 1981, showed a worst-case ratio growing like a power of nn), and then the 12 OPT\frac{1}{2}\,\text{OPT} bound is lost.
  • Dropping the metric assumption. On non-metric costs both the shortcutting step and the bound on the matching fail, and no constant factor is possible at all.
  • Expecting 32\frac{3}{2} in practice. In the experiments of Johnson and McGeoch on random Euclidean instances, Christofides' tours are typically about 10% above the Held-Karp lower bound, worse than local search heuristics such as 2-opt or Lin-Kernighan started from it. Its value is the guarantee, and the tour is a good starting point for local search.

Beyond 3/2

For 45 years nobody improved the factor for general metric TSP. Then Karlin, Klein and Oveis Gharan (announced in 2020, published at STOC 2021) gave a randomized algorithm with ratio 32−ε0\frac{3}{2} - \varepsilon_0 for a tiny constant ε0>10−36\varepsilon_0 > 10^{-36}, later derandomized. It samples the spanning tree from a maximum-entropy distribution whose marginals match an optimal solution of the Held-Karp LP relaxation, then adds a matching as Christofides does; the analysis shows that the parity correction is cheaper than half the LP value by a constant fraction in expectation. The improvement is minute, but it showed that 32\frac{3}{2} is not a natural barrier.

What is known around it:

  • The Held-Karp LP (subtour elimination) has integrality gap at least 43\frac{4}{3} and at most 32\frac{3}{2} (Wolsey, 1980; Shmoys and Williamson, 1990); the conjecture that it is exactly 43\frac{4}{3} is open.
  • Unless P = NP, metric TSP has no 123122\frac{123}{122}-approximation (Karpinski, Lampis and Schmied, 2015), so it is APX-hard and has no PTAS.
  • For points in the Euclidean plane there is a PTAS (Euclidean TSP: the Idea of Arora's PTAS).
  • For the path version (fixed endpoints s≠ts \ne t), Christofides' idea gives only 53\frac{5}{3} (Hoogeveen, 1991); a long line of work brought it down to 32\frac{3}{2} (Zenklusen, 2019).

Test yourself

Why does a perfect matching on the odd-degree vertices of the MST always exist?

  1. The MST is a path
  2. The number of odd-degree vertices of any graph is even, and the graph on them is complete
  3. Because the costs are metric
  4. Because nn is even

Why does the minimum perfect matching on OO cost at most 12OPT\frac{1}{2}\text{OPT}?

  1. Because it has at most n2\frac{n}{2} edges
  2. Shortcutting an optimal tour to OO gives a cycle of cost at most OPT, which splits into two perfect matchings on OO
  3. Because the MST costs at most 12OPT\frac{1}{2}\text{OPT}
  4. Because matching edges are shorter than tree edges

What did Karlin, Klein and Oveis Gharan prove about metric TSP?

  1. A PTAS
  2. A (32−ε0)(\frac{3}{2} - \varepsilon_0)-approximation for a constant ε0>10−36\varepsilon_0 > 10^{-36}, using max-entropy random spanning trees
  3. That 32\frac{3}{2} is optimal unless P = NP
  4. An exact polynomial algorithm for planar instances