Purpose: Count spanning trees of a graph as a determinant. This is the general statement; Kirchhoff’s theorem is the classical undirected case.

Undirected version

Build the Laplacian , where is the diagonal degree matrix and the adjacency matrix. Then:

for any , where deletes row and column . All such cofactors are equal.

Weighted version. Set and . The same cofactor now computes

which counts trees when all , and is the tool for “sum over spanning trees” problems.

Directed version (Tutte)

For counting arborescences rooted at (every vertex reaches , or reaches every vertex, depending on orientation):

  • in-trees (all edges point toward ): use and delete row/column ;
  • out-trees (all edges point away from ): use and delete row/column .

Unlike the undirected case, the cofactor depends on — different roots give different counts.

Code

// count spanning trees mod p (p prime), n <= ~300
long long countSpanningTrees(int n, vector<vector<long long>> L, long long MOD) {
    // delete last row and column
    int m = n - 1;
    long long det = 1;
    for (int i = 0; i < m; i++) {
        int piv = -1;
        for (int r = i; r < m; r++) if (L[r][i] % MOD) { piv = r; break; }
        if (piv < 0) return 0;
        if (piv != i) { swap(L[piv], L[i]); det = MOD - det; }
        det = det * L[i][i] % MOD;
        long long inv = powmod(L[i][i], MOD - 2, MOD);
        for (int c = i; c < m; c++) L[i][c] = L[i][c] * inv % MOD;
        for (int r = i + 1; r < m; r++) {
            long long f = L[r][i];
            if (!f) continue;
            for (int c = i; c < m; c++)
                L[r][c] = (L[r][c] - f * L[i][c]) % MOD;
        }
    }
    return (det % MOD + MOD) % MOD;
}

Build with L[u][u]++, L[v][v]++, L[u][v]--, L[v][u]-- for each undirected edge (all taken mod MOD, so use (x % MOD + MOD) % MOD).

Complexity

Consequences

  • Cayley’s formula. For , the Laplacian is ; a cofactor gives labelled trees on vertices — the shortest known proof.
  • Complete bipartite graph. has spanning trees.
  • Number of Eulerian circuits — the BEST theorem combines the arborescence count with .
  • Effective resistance. , connecting spanning trees to electrical networks.

Variants / Use Cases

  • Kirchhoff’s Theorem — the undirected statement in detail
  • Prüfer codes — a bijective proof of Cayley’s formula, and the way to sample random labelled trees
  • Chu-Liu/Edmonds — finds the minimum arborescence rather than counting them
  • Random spanning tree sampling — Wilson’s algorithm (loop-erased random walk) samples uniformly without any determinant
  • Counting problems mod a prime — the standard contest framing, since the true count is astronomically large