TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Perfect Matchings and the Tutte Matrix

Perfect Matchings and the Tutte Matrix

A perfect matching of a graph is a set of edges that covers every vertex exactly once. For bipartite graphs it can be found with flows (Maximum Bipartite Matching); for general graphs Edmonds' blossom algorithm (1965) does it in polynomial time but is intricate. There is a completely different, algebraic route: a graph has a perfect matching exactly when a certain symbolic determinant is not identically zero. Combined with the Schwartz-Zippel lemma, that gives a randomized test that is a few lines of linear algebra, and that parallelises well. The idea is due to Tutte (1947), Edmonds (1967) and Lovász (1979).

Bipartite graphs: the Edmonds matrix

Let GG be bipartite with sides {u0,…,un−1}\{u_0, \ldots, u_{n-1}\} and {v0,…,vn−1}\{v_0, \ldots, v_{n-1}\}. Its Edmonds matrix AA has an indeterminate xijx_{ij} in position (i,j)(i, j) if uivju_i v_j is an edge, and 0 otherwise. Expanding the determinant over permutations,

det⁡A=∑σsgn⁡(σ)∏i=0n−1Ai,σ(i),\det A = \sum_{\sigma} \operatorname{sgn}(\sigma) \prod_{i=0}^{n-1} A_{i,\sigma(i)} ,

a term is nonzero exactly when every uivσ(i)u_i v_{\sigma(i)} is an edge, that is, when σ\sigma describes a perfect matching. Different permutations give different monomials, so nothing cancels: det⁡A≢0\det A \not\equiv 0 if and only if GG has a perfect matching.

General graphs: the Tutte matrix

For a general graph on vertices 0,…,n−10, \ldots, n-1 (nn even), the Tutte matrix TT is skew-symmetric:

Tij={xijif ij∈E and i<j,−xjiif ij∈E and i>j,0otherwise.T_{ij} = \begin{cases} x_{ij} & \text{if } ij \in E \text{ and } i < j, \\ -x_{ji} & \text{if } ij \in E \text{ and } i > j, \\ 0 & \text{otherwise.} \end{cases}

Theorem (Tutte, 1947). det⁡T≢0\det T \not\equiv 0 as a polynomial if and only if GG has a perfect matching.

Proof sketch

A permutation σ\sigma contributes a nonzero term only if every pair i,σ(i)i, \sigma(i) is an edge (fixed points are excluded, since Tii=0T_{ii} = 0). Decompose σ\sigma into cycles.

If GG has a perfect matching MM, let σ\sigma swap the endpoints of every edge of MM. Its term is ∏ij∈M(−xij2)\prod_{ij \in M} (-x_{ij}^2) up to sign. Any other permutation producing the same monomial must also use exactly the edges of MM in both directions, so it is σ\sigma itself; the monomial survives and det⁡T≠0\det T \ne 0.

Conversely, pair up the permutations that contain an odd cycle: reverse the odd cycle containing the smallest vertex that lies on an odd cycle. Reversing an odd cycle of a skew-symmetric matrix multiplies its product by (−1)length=−1(-1)^{\text{length}} = -1 and keeps the sign of the permutation, so the two terms cancel. The surviving terms come from permutations with only even cycles, and every even cycle of edges contains a perfect matching of its vertices (take every other edge). So a nonzero determinant implies a perfect matching.

Over a field, det⁡T\det T is the square of a polynomial called the Pfaffian of TT, whose terms correspond to perfect matchings one by one.

The randomized test

det⁡T\det T has total degree nn (every term has one entry per row). By Schwartz-Zippel, substituting independent uniform values from Zp\mathbb{Z}_p for the indeterminates and computing the determinant numerically, in O(n3)O(n^3) time by Gaussian elimination, gives:

  • if GG has no perfect matching, the result is always 0;
  • if GG has one, the result is 0 with probability at most n/pn/p.
text
HAS-PERFECT-MATCHING(G, p)          // Lovász 1979; one-sided error n/p
0  build T with T[i][j] = r_ij, T[j][i] = -r_ij for every edge ij (i < j), r_ij uniform in Z_p
1  return DET(T) mod p != 0

A "yes" answer is always correct; a "no" answer can be wrong with probability at most n/pn/p, about 10−1610^{-16} for p=261−1p = 2^{61} - 1 and nn in the thousands. More generally, the rank of the randomly substituted Tutte matrix is twice the size of a maximum matching with the same probability (Lovász, 1979), so the test also measures how large a matching is.

The program compares the test with brute-force matching search on small graphs: the Petersen graph (it has perfect matchings), two disjoint triangles (no perfect matching: each triangle has an odd number of vertices), a star with three leaves plus a separate edge (no perfect matching: the centre can match only one leaf), and a 6-cycle with a pendant path.

python · try it yourself
import random

P = 2 ** 61 - 1

def rank_mod(M, p=P):
    M = [row[:] for row in M]
    rank, rows, cols = 0, len(M), len(M[0])
    for c in range(cols):
        piv = next((r for r in range(rank, rows) if M[r][c] % p), None)
        if piv is None:
            continue
        M[rank], M[piv] = M[piv], M[rank]
        inv = pow(M[rank][c], p - 2, p)
        for r in range(rows):
            if r != rank and M[r][c] % p:
                f = M[r][c] * inv % p
                M[r] = [(a - f * b) % p for a, b in zip(M[r], M[rank])]
        rank += 1
    return rank

def tutte(n, edges, rng):
    T = [[0] * n for _ in range(n)]
    for i, j in edges:
        r = rng.randrange(1, P)
        T[i][j], T[j][i] = r, (-r) % P
    return T

def max_matching_brute(n, edges):
    best = 0
    def grow(k, used, size):
        nonlocal best
        best = max(best, size)
        for t in range(k, len(edges)):
            i, j = edges[t]
            if i not in used and j not in used:
                grow(t + 1, used | {i, j}, size + 1)
    grow(0, frozenset(), 0)
    return best

petersen = [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)] + [(5 + i, 5 + (i + 2) % 5) for i in range(5)]
graphs = {
    "Petersen graph (10 vertices)": (10, petersen),
    "two disjoint triangles": (6, [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5)]),
    "star K_1,3 plus an edge": (6, [(0, 1), (0, 2), (0, 3), (4, 5)]),
    "6-cycle with a 2-vertex tail": (8, [(i, (i + 1) % 6) for i in range(6)] + [(0, 6), (6, 7)]),
}
rng = random.Random(80)
for name, (n, edges) in graphs.items():
    rk = rank_mod(tutte(n, edges, rng))
    print(f"{name:30}: rank(T) = {rk:2} -> matching size {rk // 2}, perfect: {rk == n}; "
          f"brute force: {max_matching_brute(n, edges)}")
Petersen graph (10 vertices)  : rank(T) = 10 -> matching size 5, perfect: True; brute force: 5
two disjoint triangles        : rank(T) =  4 -> matching size 2, perfect: False; brute force: 2
star K_1,3 plus an edge       : rank(T) =  4 -> matching size 2, perfect: False; brute force: 2
6-cycle with a 2-vertex tail  : rank(T) =  8 -> matching size 4, perfect: True; brute force: 4

The rank halves exactly to the size of a maximum matching in every case.

The error is one-sided, and Schwartz-Zippel bounds it

With a small prime the test can miss a perfect matching: the random determinant may vanish by accident. The lemma bounds that probability by n/pn/p, since det⁡T\det T has degree nn. The program measures the false-"no" rate on the Petersen graph (n=10n = 10) for small primes, and confirms that graphs without a perfect matching are never reported as having one.

python · try it yourself
import random

def det_mod(M, p):
    M = [row[:] for row in M]
    n, det = len(M), 1
    for c in range(n):
        piv = next((r for r in range(c, n) if M[r][c] % p), None)
        if piv is None:
            return 0
        if piv != c:
            M[c], M[piv] = M[piv], M[c]
            det = -det
        det = det * M[c][c] % p
        inv = pow(M[c][c], p - 2, p)
        for r in range(c + 1, n):
            f = M[r][c] * inv % p
            M[r] = [(a - f * b) % p for a, b in zip(M[r], M[c])]
    return det % p

def random_tutte(n, edges, p, rng):
    T = [[0] * n for _ in range(n)]
    for i, j in edges:
        r = rng.randrange(p)
        T[i][j], T[j][i] = r, (-r) % p
    return T

petersen = [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)] + [(5 + i, 5 + (i + 2) % 5) for i in range(5)]
triangles = [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5)]
rng = random.Random(81)
trials = 400
print("   p   Petersen: false 'no' rate   bound n/p   two triangles: false 'yes'")
for p in [5, 11, 31, 101]:
    miss = sum(det_mod(random_tutte(10, petersen, p, rng), p) == 0 for _ in range(trials))
    fake = sum(det_mod(random_tutte(6, triangles, p, rng), p) != 0 for _ in range(trials))
    print(f"{p:4}   {miss / trials:26.3f}   {min(1, 10 / p):9.3f}   {fake:26}")
   p   Petersen: false 'no' rate   bound n/p   two triangles: false 'yes'
   5                        0.292       1.000                            0
  11                        0.105       0.909                            0
  31                        0.025       0.323                            0
 101                        0.007       0.099                            0

Here the values are drawn from all of Zp\mathbb{Z}_p, including 0, so the lemma applies with ∣S∣=p\lvert S \rvert = p. The measured error is well below n/pn/p, and graphs without a perfect matching never produce a nonzero determinant.

In C++

The test in C++: fill the Tutte matrix with random residues modulo p=261−1p = 2^{61} - 1 (fixed-seed std::mt19937_64), and compute the determinant by Gaussian elimination, with 128-bit products. It checks random graphs on 40 vertices with a planted perfect matching, and the same graphs with one vertex's edges deleted (then no perfect matching exists).

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <random>
#include <utility>
#include <vector>

using u64 = std::uint64_t;
const u64 P = (1ULL << 61) - 1;
std::mt19937_64 rng(80);

u64 mul(u64 a, u64 b) { return (unsigned __int128)a * b % P; }
u64 power(u64 a, u64 e) { u64 r = 1; for (; e; e >>= 1, a = mul(a, a)) if (e & 1) r = mul(r, a); return r; }

u64 det_mod(std::vector<std::vector<u64>> m) {
    int n = m.size();
    u64 det = 1;
    for (int c = 0; c < n; ++c) {
        int piv = -1;
        for (int r = c; r < n; ++r) if (m[r][c]) { piv = r; break; }
        if (piv < 0) return 0;
        if (piv != c) { std::swap(m[piv], m[c]); det = (P - det) % P; }
        det = mul(det, m[c][c]);
        u64 inv = power(m[c][c], P - 2);
        for (int r = c + 1; r < n; ++r) {
            u64 f = mul(m[r][c], inv);
            for (int k = c; k < n; ++k) m[r][k] = (m[r][k] + P - mul(f, m[c][k])) % P;
        }
    }
    return det;
}

bool has_perfect_matching(int n, const std::vector<std::pair<int, int>>& edges) {
    std::vector<std::vector<u64>> t(n, std::vector<u64>(n, 0));
    for (auto [i, j] : edges) {
        u64 r = 1 + rng() % (P - 1);
        t[i][j] = r;
        t[j][i] = P - r;
    }
    return det_mod(t) != 0;
}

int main() {
    const int n = 40;
    for (int g = 0; g < 3; ++g) {
        std::vector<std::pair<int, int>> e;
        for (int i = 0; i < n; i += 2) e.push_back({i, i + 1});          // planted matching
        for (int k = 0; k < 60; ++k) {
            int a = rng() % n, b = rng() % n;
            if (a != b && (a | 1) != (b | 1)) e.push_back({a, b});
        }
        std::vector<std::pair<int, int>> cut;                           // isolate vertex 0
        for (auto [a, b] : e) if (a != 0 && b != 0) cut.push_back({a, b});
        std::printf("graph %d: %zu edges, perfect matching: %s; vertex 0 isolated: %s\n", g, e.size(),
                    has_perfect_matching(n, e) ? "yes" : "no", has_perfect_matching(n, cut) ? "yes" : "no");
    }
}
graph 0: 74 edges, perfect matching: yes; vertex 0 isolated: no
graph 1: 78 edges, perfect matching: yes; vertex 0 isolated: no
graph 2: 79 edges, perfect matching: yes; vertex 0 isolated: no

From testing to finding, and parallelism

The determinant test decides existence. To find a perfect matching, one can delete edges one at a time and keep the deletion whenever a matching still exists, at the cost of mm determinant computations; Rabin and Vazirani (1989) read the matching off the inverse of TT instead. Mucha and Sankowski (2004) found a perfect matching in O(nω)O(n^\omega) time, where ω<2.372\omega < 2.372 is the matrix-multiplication exponent, faster than the O(mn)O(m\sqrt n) of Micali and Vazirani on dense graphs.

The algebraic approach also gave the first fast parallel algorithms. Determinants can be computed in O(log⁡2n)O(\log^2 n) parallel time, so perfect-matching existence is in randomized NC. Finding one in parallel needed an extra trick, the isolation lemma of Mulmuley, Vazirani and Vazirani (1987): if each edge gets a random weight from {1,…,2m}\{1, \ldots, 2m\}, then with probability at least 1/21/2 the minimum-weight perfect matching is unique, and a unique matching can be extracted from a single determinant with weights 2w(e)2^{w(e)}. Whether perfect matching is in deterministic NC is still open (quasi-NC algorithms are known: Fenner, Gurjar and Thierauf, 2016, for bipartite graphs, and Svensson and Tarnawski, 2017, for general graphs).

Test yourself

In the Edmonds matrix of a bipartite graph, why can no two nonzero terms of the determinant cancel?

  1. Because all entries are positive
  2. Because distinct permutations give distinct monomials in the indeterminates xijx_{ij}
  3. Because the matrix is symmetric
  4. Because the field has characteristic 2

The randomly substituted Tutte determinant is nonzero. What can you conclude?

  1. The graph certainly has a perfect matching
  2. The graph has a perfect matching with probability at least 1−n/p1 - n/p
  3. Nothing
  4. The graph has no perfect matching

Why does the Tutte matrix need to be skew-symmetric for general graphs?

  1. To make the determinant easier to compute
  2. So that terms coming from permutations with odd cycles cancel in pairs
  3. Because graphs are undirected
  4. To keep the entries small

What does the rank of a randomly substituted Tutte matrix tell you, with high probability?

  1. The number of vertices
  2. Twice the size of a maximum matching
  3. The number of perfect matchings
  4. The chromatic number