TExcelTAD
Home › Linear Programming & Duality for Algorithms › Totally Unimodular Matrices

Totally Unimodular Matrices

Why do maximum flows, bipartite matchings and shortest paths come out integral when solved as LPs, while vertex cover on a triangle comes out at one half? The answer is a property of the constraint matrix alone, total unimodularity. For a totally unimodular matrix, every vertex of the polyhedron is integral for every integral right-hand side, so the LP relaxation solves the integer problem exactly, and LP duality turns into a min-max theorem between two combinatorial problems. This lesson proves the theorem with Cramer's rule, implements a brute-force TU test in Python and C++, and shows the effect on vertices.

Definition and the main theorem

A matrix AA with entries in {0,1,−1}\{0, 1, -1\} is totally unimodular (TU) if every square submatrix has determinant 00, 11 or −1-1. (Square submatrix means any choice of kk rows and kk columns, not necessarily contiguous, for every kk.) In particular every entry, a 1×11 \times 1 submatrix, is 00 or ±1\pm 1.

Theorem (Hoffman and Kruskal, 1956). If AA is totally unimodular and bb is integral, every vertex of P={x:Ax≤b}P = \{ x : Ax \le b \} is integral. The same holds for {x:Ax≤b, x≥0}\{ x : Ax \le b,\ x \ge 0 \}, {x:Ax=b, x≥0}\{ x : Ax = b,\ x \ge 0 \} and for added integral bounds ℓ≤x≤u\ell \le x \le u.

Proof. A vertex vv of PP is the unique solution of a system A′v=b′A' v = b' where A′A' is a non-singular square submatrix of AA (the rows of nn linearly independent tight constraints) and b′b' the corresponding entries of bb. By Cramer's rule,

vj=det⁡Aj′det⁡A′,v_j = \frac{\det A'_j}{\det A'},

where Aj′A'_j is A′A' with column jj replaced by b′b'. The denominator is ±1\pm 1 because AA is TU, and the numerator is an integer because Aj′A'_j has integer entries. So vjv_j is an integer. For the other forms: if AA is TU then so are (A−I)\binom{A}{-I}, (AI)\binom{A}{I} and (A−A)\binom{A}{-A} (a square submatrix that uses identity rows can be expanded along those rows, leaving a square submatrix of AA up to sign), so those polyhedra are of the form {x:A′′x≤b′′}\{ x : A'' x \le b'' \} with A′′A'' TU. □\square

Hoffman and Kruskal also proved the converse: if {x:Ax≤b, x≥0}\{ x : Ax \le b,\ x \ge 0 \} is integral for every integral bb, then AA is TU. So TU is exactly the right condition for this "integral for all right-hand sides" property.

Two consequences for duality:

  • AA is TU if and only if ATA^T is (determinants are invariant under transposition). So when AA is TU, both max⁡{cTx:Ax≤b, x≥0}\max \{ c^T x : Ax \le b,\ x \ge 0 \} and its dual min⁡{bTy:ATy≥c, y≥0}\min \{ b^T y : A^T y \ge c,\ y \ge 0 \} have integral optimal solutions whenever bb and cc are integral and the optima exist.
  • This is how max-flow min-cut and König's theorem come out of LP duality: the min-max relation is strong duality, and TU makes both optima integral, hence combinatorial.

Testing total unimodularity

The definition gives an algorithm: compute the determinant of every square submatrix. That is exponential (an m×nm \times n matrix has ∑k(mk)(nk)\sum_k \binom{m}{k}\binom{n}{k} square submatrices), but fine for small examples, and it finds a witness when the matrix is not TU. Determinants are computed exactly with the fraction-free Bareiss elimination.

python · try it yourself
from itertools import combinations

def det(M):
    """Exact integer determinant by Bareiss' fraction-free elimination."""
    M = [row[:] for row in M]
    n, sign, prev = len(M), 1, 1
    for k in range(n - 1):
        if M[k][k] == 0:
            swap = next((r for r in range(k + 1, n) if M[r][k] != 0), None)
            if swap is None:
                return 0
            M[k], M[swap] = M[swap], M[k]
            sign = -sign
        for i in range(k + 1, n):
            for j in range(k + 1, n):
                M[i][j] = (M[i][j] * M[k][k] - M[i][k] * M[k][j]) // prev
        prev = M[k][k]
    return sign * M[n - 1][n - 1]

def tu_witness(A):
    m, n = len(A), len(A[0])
    for k in range(1, min(m, n) + 1):
        for R in combinations(range(m), k):
            for C in combinations(range(n), k):
                d = det([[A[i][j] for j in C] for i in R])
                if d not in (-1, 0, 1):
                    return R, C, d
    return None

def incidence(nv, edges):
    return [[1 if v in e else 0 for e in edges] for v in range(nv)]

examples = {
    "4-cycle (bipartite)": incidence(4, [(0, 1), (1, 2), (2, 3), (3, 0)]),
    "triangle": incidence(3, [(0, 1), (1, 2), (0, 2)]),
    "5-cycle": incidence(5, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]),
    "directed graph (node-arc)": [[1, 1, 0, 0, 0], [-1, 0, 1, 1, 0], [0, -1, -1, 0, 1], [0, 0, 0, -1, -1]],
    "intervals [1,2],[2,4],[3,3],[1,4]": [[1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 1, 1], [0, 1, 0, 1]],
}
for name, A in examples.items():
    w = tu_witness(A)
    print(f"{name:34} " + ("TU" if w is None else f"not TU: rows {w[0]}, columns {w[1]} have det {w[2]}"))
4-cycle (bipartite)                TU
triangle                           not TU: rows (0, 1, 2), columns (0, 1, 2) have det 2
5-cycle                            not TU: rows (0, 1, 2, 3, 4), columns (0, 1, 2, 3, 4) have det 2
directed graph (node-arc)          TU
intervals [1,2],[2,4],[3,3],[1,4]  TU

The odd cycles fail on the whole matrix: the incidence matrix of an odd cycle has determinant ±2\pm 2. In fact a graph's incidence matrix is TU exactly when the graph is bipartite, because any odd cycle gives such a submatrix and, conversely, bipartite incidence matrices are TU (next lesson).

In C++

The same exhaustive test, with submatrices chosen by bit masks and Bareiss elimination on 64-bit integers.

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

using Mat = std::vector<std::vector<long long>>;

long long det(Mat M) {
    int n = M.size();
    long long sign = 1, prev = 1;
    for (int k = 0; k < n - 1; k++) {
        if (M[k][k] == 0) {
            int s = -1;
            for (int r = k + 1; r < n; r++) if (M[r][k] != 0) { s = r; break; }
            if (s < 0) return 0;
            std::swap(M[k], M[s]);
            sign = -sign;
        }
        for (int i = k + 1; i < n; i++)
            for (int j = k + 1; j < n; j++) M[i][j] = (M[i][j] * M[k][k] - M[i][k] * M[k][j]) / prev;
        prev = M[k][k];
    }
    return sign * M[n - 1][n - 1];
}

// Returns the largest |det| over all square submatrices (TU iff it is at most 1).
long long max_abs_minor(const Mat& A) {
    int m = A.size(), n = A[0].size();
    long long worst = 0;
    for (int rm = 1; rm < (1 << m); rm++)
        for (int cm = 1; cm < (1 << n); cm++) {
            if (__builtin_popcount(rm) != __builtin_popcount(cm)) continue;
            Mat S;
            for (int i = 0; i < m; i++) if (rm >> i & 1) {
                S.emplace_back();
                for (int j = 0; j < n; j++) if (cm >> j & 1) S.back().push_back(A[i][j]);
            }
            long long d = det(S);
            if (d < 0) d = -d;
            if (d > worst) worst = d;
        }
    return worst;
}

int main() {
    std::vector<std::pair<const char*, Mat>> ex = {
        {"4-cycle", {{1, 0, 0, 1}, {1, 1, 0, 0}, {0, 1, 1, 0}, {0, 0, 1, 1}}},
        {"triangle", {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}}},
        {"node-arc", {{1, 1, 0, 0, 0}, {-1, 0, 1, 1, 0}, {0, -1, -1, 0, 1}, {0, 0, 0, -1, -1}}},
        {"not TU", {{1, 1, 0}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}},
    };
    for (auto& [name, A] : ex) {
        long long w = max_abs_minor(A);
        std::printf("%-9s largest |minor| = %lld -> %s\n", name, w, w <= 1 ? "TU" : "not TU");
    }
}
4-cycle   largest |minor| = 1 -> TU
triangle  largest |minor| = 2 -> not TU
node-arc  largest |minor| = 1 -> TU
not TU    largest |minor| = 2 -> not TU

Exhaustive testing is exponential, but TU matrices can be recognised in polynomial time: Seymour's decomposition theorem (1980) shows that every TU matrix is built from network matrices and two special 5×55 \times 5 matrices by simple composition operations, and this yields a polynomial recognition algorithm (Truemper, 1990, gives an O((m+n)3)O((m + n)^3) version).

TU at work: integral vertices for free

The program solves the same kind of LP twice with random integer data: the assignment LP (3×33 \times 3 bipartite, TU) and the fractional vertex cover LP of a 5-cycle (not TU), and counts how often the solver's optimal vertex is integral. The simplex-type HiGHS solver returns a vertex, so the count shows the vertices, not luck.

python · try it yourself
import random
from scipy.optimize import linprog

rng = random.Random(1956)
cells = [(i, j) for i in range(3) for j in range(3)]
rows = [[1 if c[0] == i else 0 for c in cells] for i in range(3)] + [[1 if c[1] == j else 0 for c in cells] for j in range(3)]
c5 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
cover = [[-1 if v in e else 0 for v in range(5)] for e in c5]

integral = {"assignment": 0, "vertex cover of C5": 0}
trials = 50
for _ in range(trials):
    cost = [rng.randint(1, 20) for _ in cells]
    r = linprog(cost, A_eq=rows, b_eq=[1] * 6, bounds=[(0, None)] * 9, method="highs-ds")
    integral["assignment"] += all(abs(v - round(v)) < 1e-9 for v in r.x)
    w = [rng.randint(1, 20) for _ in range(5)]
    r = linprog(w, A_ub=cover, b_ub=[-1] * 5, bounds=[(0, None)] * 5, method="highs-ds")
    integral["vertex cover of C5"] += all(abs(v - round(v)) < 1e-9 for v in r.x)
for name, k in integral.items():
    print(f"{name:20} integral optimal vertex in {k} of {trials} random instances")
assignment           integral optimal vertex in 50 of 50 random instances
vertex cover of C5   integral optimal vertex in 36 of 50 random instances

Every assignment optimum is a permutation matrix, as TU guarantees. For the 5-cycle the outcome depends on the weights: when some vertex is expensive enough, the half-integral vertex (12,…,12)(\frac{1}{2}, \ldots, \frac{1}{2}) or another fractional vertex wins.

Test yourself

What is the definition of a totally unimodular matrix?

  1. det⁡A=±1\det A = \pm 1
  2. Every square submatrix has determinant 00, 11 or −1-1
  3. All entries are 00 or 11
  4. AA is square and invertible

Which tool proves that TU matrices give integral vertices?

  1. Farkas' lemma
  2. Cramer's rule: a vertex solves A′v=b′A'v = b' with det⁡A′=±1\det A' = \pm 1
  3. The ellipsoid method
  4. Complementary slackness

Which graphs have a totally unimodular vertex-edge incidence matrix?

  1. All graphs
  2. Exactly the bipartite graphs
  3. Exactly the trees
  4. Exactly the complete graphs

If AA is TU, which of these matrices is also TU?

  1. 2A2A
  2. ATA^T and (AI)\binom{A}{I}
  3. A+IA + I
  4. A2A^2