The matrix-tree theorem solves the problem of counting the number of spanning trees of a graph.
Notation in this article
The graphs in this article, whether undirected or directed, may have multiple edges, but are assumed to have no self-loops by default.
The case of self-loops
Self-loops affect neither the number of spanning trees nor the calculation of the Laplace matrix below, so the matrix-tree theorem remains valid in the presence of self-loops. There is no need to delete self-loops during computation. If self-loops are deleted, it affects the use of the matrix-tree theorem under the BEST theorem to count the number of Eulerian circuits in a directed graph.
Undirected graphs
Let be an undirected graph with vertices. Define its degree matrix by
Let be the number of edges connecting vertices and , and define the adjacency matrix by
Define the Laplace matrix (also called the Kirchhoff matrix) by
Let the number of all spanning trees of be .
Directed graphs
Let be a directed graph with vertices. Define its out-degree matrix by
Define the in-degree matrix similarly.
Let be the number of directed edges from vertex to vertex , and define the adjacency matrix by
Define the out-degree Laplace matrix by
Define the in-degree Laplace matrix by
Let the number of all arborescences of rooted at be . An arborescence is a graph whose underlying graph is a tree and whose edges all point toward the root.
Let the number of all anti-arborescences of rooted at be . An anti-arborescence is a graph whose underlying graph is a tree and whose edges all point away from the root.
Theorem statements
The matrix-tree theorem has several forms.
Define , and for a matrix , let its submatrix be the matrix formed by selecting the elements .
Theorem 1 (matrix-tree theorem, undirected graphs, determinant form)
For an undirected graph and any ,
In other words, all principal minors of order of the Laplace matrix of an undirected graph are equal, and all equal the number of spanning trees of the graph.
Corollary 1 (matrix-tree theorem, undirected graphs, eigenvalue form)
Let be the eigenvalues of , of which there are . Then
Theorem 2 (matrix-tree theorem, directed graphs, arborescences, determinant form)
For a directed graph and any ,
In other words, the principal minor obtained by deleting row and column from the out-degree Laplace matrix of a directed graph equals the number of arborescences rooted at .
Therefore, to count all arborescences of a graph, it suffices to enumerate every root and sum .
Theorem 3 (matrix-tree theorem, directed graphs, anti-arborescences, determinant form)
For a directed graph and any ,
In other words, the principal minor obtained by deleting row and column from the in-degree Laplace matrix of a directed graph equals the number of anti-arborescences rooted at .
Therefore, to count all anti-arborescences of a graph, it suffices to enumerate every root and sum .
Note
An arborescence is also called an in-tree, but because the out-degree is used when computing in-trees, the term arborescence is used here to avoid confusion between and .
Proof of the theorems
The forms of the theorems above are extremely similar. Here we give a unified proof and extend the previous conclusions to weighted graphs.
The proof proceeds roughly as follows:
- First, every case can be reduced to counting arborescences in a directed graph;
- use matrix language to give necessary and sufficient conditions for the selected edges to form an arborescence;
- connect the edge-selection operation with the determinant of the Laplace matrix using the Cauchy–Binet formula;
- finally, convert the determinant-form conclusion into the eigenvalue-form conclusion.
Lemma: the Cauchy–Binet formula
Lemma 1 (Cauchy–Binet)
Given an matrix and an matrix ,
where the summation means that ranges over all subsets of of size . If , then necessarily .
Proof (combinatorial viewpoint)
Following the model from 「NOI2021」Path Intersections, first consider the following combinatorial interpretation of a determinant. For an matrix , construct a directed acyclic graph . Its vertex set is , namely two columns of points in the plane. Denote the points in the left column by and those in the right column by ; the directed edge set is , and assign edge weight . In this graph, call a subset of edges, , a path family if its starting points are pairwise distinct and its ending points are also pairwise distinct. Clearly, path families and permutations of , denoted , are in one-to-one correspondence. Notice that when a path family is drawn in the plane, its edges may intersect pairwise, and the number of intersection points, counted with multiplicity, equals the inversion number of . This is because edges and intersect if and only if , which is precisely an inversion pair. For convenience, call the parity of the inversion number of the corresponding permutation, equivalently the parity of the number of intersections in the path family, the parity of the path family. Thus, if these path families are counted by weight, the number of path families with an even number of intersections minus the number with an odd number of intersections gives the Leibniz expansion of the determinant:
where is the permutation group on , and is the sign of permutation (it equals when the inversion number is even and when the inversion number is odd).
Once the combinatorial meaning of the determinant is understood, the Cauchy–Binet formula can be proved using the following combinatorial model. For an matrix and an matrix , construct a directed acyclic graph . Its vertex set is , where , , and ; its directed edge set is , where and , with edge weights and , respectively. Again consider path families from through to , with paths pairwise sharing no vertices; count them by weight and subtract the count of path families with an odd number of intersections from the count with an even number of intersections. We now show that the two sides of the Cauchy–Binet formula compute this number in two ways.
For the left-hand side, based on the graph described above, construct a new graph whose vertex set is and whose edge set is . Assign edge the weight , namely, in the original graph , the weighted count of simple paths from to . This edge weight is exactly . This amounts to simplifying the three-layer graph into a two-layer graph. However, path families in the two-layer graph do not correspond one-to-one with path families in the three-layer graph . Since each path in the two-layer graph corresponds to several simple paths in the three-layer graph, counting path families in the two-layer graph requires multiplying their weights, which amounts to pairing the corresponding path sets in the three-layer graph. This inevitably produces cases in which paths share an intermediate stop. However, pairs of paths sharing an intermediate stop do not contribute to the final answer: for , , and any intermediate point , there are two pairs of simple paths, and , but the parities of their numbers of intersections in the three-layer graph are necessarily opposite, because if only the starting and ending points are considered, the two path pairs exchange their endpoints. Therefore, these paths sharing an intermediate stop cancel in pairs when path families are counted in the simplified two-layer graph. For the remaining cases, once the starting and ending points of two paths are fixed, the parity of the number of their intersections does not change regardless of how the intermediate points are selected, as long as the same point is not selected twice. Thus, for each path family in , all corresponding path families in the original graph have the same parity. Consequently, provides one way to compute the difference in the number of path families described above.
For the right-hand side, it enumerates all possible combinations of intermediate points. Given any intermediate-point set with , consider path families from to and from to , respectively. They can be joined to obtain a path family from to , and the composition of the permutations corresponding to the first two path families is exactly the permutation corresponding to the resulting path family, so the product of the parities of the first two path families equals the parity of the resulting path family. Therefore, the difference in the counts of all path families whose intermediate-point set is is exactly the product of the difference in the counts of path families from to and from to . Summing over all possible gives the right-hand side, so it is precisely the difference in the number of path families described above.
Proof (algebraic viewpoint)
The combinatorial proof above can in fact be translated into an algebraic proof word for word. Here we instead give a more technically involved algebraic proof, using several common results. When , the determinant is zero because
When , the Cauchy–Binet formula is simply the fact that the determinant of a product of square matrices equals the product of their determinants.
When , note that
It is also known that, for , the coefficient of is the sum of all principal minors of of order . Therefore, comparing coefficients on both sides of the equation above gives
Here, the second equality uses the result for the case .
Characterizing graph structure with incidence matrices
For a directed graph with vertices and edges, assign each edge an edge weight . We can then define the out-incidence matrix
and the in-incidence matrix
Each row records one edge: the out-incidence matrix records the starting point of the edge, while the in-incidence matrix records its ending point.
A direct calculation gives
Consequently,
The Cauchy–Binet formula above shows that a principal minor of the Laplace matrix is actually a sum over a series of substructures. Each substructure reflects a property of the corresponding subgraph.
Lemma 2
For and one of its subgraphs , if it satisfies , then the subgraph is a rooted forest with as its roots if and only if
is nonzero. Moreover, when this expression is nonzero, it necessarily equals ; denote it by .
Proof
Without loss of generality, assume . By the multilinearity of determinants, each determinant can have factored out of every row, and the product of these factors is .
First analyze the conditions under which the two factors are zero. Each row of the first factor has at most one nonzero entry, namely . If any row is all zero, the determinant must be zero. Thus, the determinant is nonzero if and only if every row has exactly one ; that is, every vertex in is the starting point of exactly one edge in , and no two edges share the same starting point. If is a rooted forest with as its roots, a necessary condition is that every non-root vertex has exactly one outgoing edge, which necessarily makes this factor nonzero; but the converse does not always hold, because it does not guarantee the absence of cycles, so the second factor must also be examined. Note that the endpoints of edges in need not lie in .
Assume that the first factor is nonzero. Then the subgraph is a rooted forest if and only if contains no cycle. In this case, every row of the latter expression has one , but may have either one or zero entries. For an edge whose endpoint is also in , if the endpoint of is the starting point of , add to the row for the row for ; this eliminates, in row , the . One may imagine that this row now describes the simple path formed by joining and end to end. If a new appears in the row, then the endpoint of is also in , and the position of is the endpoint of . We can therefore continue by finding the edge starting at the endpoint of and adding its row to the current row. Such an edge always exists, because the preceding argument shows that every point in is the starting point of exactly one edge in . This process continues until the row no longer contains a , which is equivalent to continuously adding new edges to the simple path . If the row then contains only one , the endpoint of is not in the selected vertex set , so the process terminates; if the last added edge happens to cancel the existing , leaving the row all zero, then the endpoint of the new edge is the starting point of the initial edge , so a cycle has appeared. Thus, the necessary and sufficient condition for the absence of cycles is that this determinant can, after the operations above, be transformed into a form in which every row has exactly one . Since these entries are at the starting points of the corresponding edges, the resulting matrix is exactly .
In summary, if is not a rooted forest, then either or ; otherwise, both are nonzero and their product is .
The matrix-tree theorem for weighted directed graphs
We can now prove the main result of this article. All the matrix-tree theorems stated earlier are special cases of this theorem.
Theorem 4 (matrix-tree theorem, weighted directed graphs, arborescences, determinant form)
For any ,
Here, is the set of arborescences of rooted at .
Proof
Let be the set of vertices other than . Then, by the Cauchy–Binet formula, the right-hand side can be written as
As ranges over all possibilities, by Lemma 2, if and only if forms a rooted forest with as its root set, that is, if and only if is an arborescence rooted at , the right-hand side accumulates .
When , every tree has weight , so the left-hand side is exactly the count of all trees, namely , which gives Theorem 2. As above, the conclusion can be directly extended to anti-arborescences, giving Theorem 3. Finally, to count spanning trees in an undirected graph, we can apply the following corollary.
Corollary 4 (matrix-tree theorem, weighted undirected graphs, determinant form)
For an undirected graph and any ,
Here, is the set of spanning trees of . This also shows that all principal minors of of order are equal.
Proof
For an undirected graph , construct a directed graph , where ; that is, every undirected edge in is split into two oppositely directed edges in the directed graph. Fix any . Then the arborescences in rooted at and the spanning trees in are in one-to-one correspondence. From the former to the latter, we only need to remove the orientations of the edges and the choice of root; from the latter to the former, we only need to start from the selected root and orient each edge toward the root. Therefore,
Here we use , which is straightforward to verify directly.
Eigenvalue form
We still begin with the result for directed graphs.
Theorem 5
For a directed graph , define the multivariate polynomial
Here, denotes the diagonal matrix whose diagonal entries are . Then,
equals the weighted count of rooted forests of whose root set is .
Proof
Following the proof of Theorem 4, let . Then the coefficient in the theorem is (this can be seen directly from the Leibniz expansion of the determinant). By the Cauchy–Binet formula, it equals
As ranges over all possibilities, by Lemma 2, the condition that forms a rooted forest with as its root set is exactly the condition for the right-hand side to accumulate .
Substitute for every indeterminate to obtain the characteristic polynomial of the Laplace matrix
Lemma 3
The Laplace matrix has at least one eigenvalue equal to zero.
Proof
It suffices to prove that its determinant is zero. Following the proofs of Theorems 4 and 5, take . Then this determinant should equal the number of rooted forests with zero trees. Such a forest does not exist, so the determinant is zero.
Corollary 5
For a directed graph , the sum of the weights of all rooted forests consisting of trees equals the coefficient
Proof
Sum over all possible choices of the roots.
Define a -spanning forest as a spanning subgraph of a graph with connected components and no cycles.
Corollary 6
For an undirected graph , let the set of its -spanning forests be . Then
Here, is the product of the numbers of vertices in each connected component of the forest . In particular, when , we have , and hence
Proof
As in the proof of Corollary 4, we can directly use the conclusion of Corollary 5. Every rooted forest consisting of trees in the directed graph corresponds to a -spanning forest in the undirected graph. However, each -spanning forest has choices of roots, so it appears in rooted forests of the directed graph.
Applications
Cayley's formula
Corollary 7 (Cayley)
There are -vertex labeled unrooted trees, of which there are .
Proof
Equivalently, it suffices to show that the number of spanning trees of the complete graph on vertices is . To this end, write its Laplace matrix as
Computing any principal minor gives
The result follows from Theorem 1.
The BEST theorem
Prerequisite: Eulerian graph
This theorem relates the number of Eulerian circuits in a directed Eulerian graph to the number of arborescences of the graph, thereby solving the problem of counting Eulerian circuits in directed graphs. Note that counting Eulerian circuits in an arbitrary undirected graph is NP-complete.
When implementing this algorithm, first determine whether the given graph is Eulerian, remove all zero-degree vertices, then build the graph and calculate the number of arborescences, and use the BEST theorem to obtain the number of Eulerian circuits. Note that if the requested number of Eulerian circuits requires starting from a given vertex, the answer must be multiplied by the out-degree of that vertex, which is equivalent to enumerating the first edge of the circuit.
Before proving the BEST theorem, we need the following result.
Property (testing whether a directed graph has an Eulerian circuit)
A directed graph has an Eulerian circuit if and only if its nonzero-degree vertices are strongly connected and the out-degree equals the in-degree at every vertex.
For an Eulerian graph, since the out-degree and in-degree are equal, we omit the superscript and write . The BEST theorem can be stated as follows.
Theorem 6 (BEST theorem)
Let be a directed Eulerian graph, and let be any vertex. Then the total number of distinct Eulerian circuits of , , is
This also shows that for any Eulerian graph and any two vertices , we have .
Proof
The basic idea of the proof is to establish a correspondence between Eulerian circuits starting at , arborescences rooted at , and permutations of the outgoing edges at each vertex. After fixing the starting vertex of the Eulerian circuit, the count to be proved should be
The combinatorial meaning of this count leads to the following construction. For an Eulerian circuit starting at , according to the order in which each edge appears in the circuit, construct
- an arborescence rooted at , consisting of the last outgoing edge at every non-root vertex, giving ;
- the ordering of all outgoing edges at the root , giving ; and
- at each non-root vertex , the ordering of all outgoing edges other than the last one, giving .
We now show that this construction gives a bijection.
In one direction, given an Eulerian circuit, we must prove that the last outgoing edges at all non-root vertices form an arborescence. By construction, every non-root vertex in the tree has exactly one outgoing edge, so it remains only to prove that these outgoing edges do not form a cycle. If all vertices are ordered according to the order of their last appearances in the Eulerian circuit, then the last outgoing edge of every non-root vertex must point to a vertex that appears strictly later in this order. If a cycle existed, it would contain a vertex that appears latest in the order; because this vertex lies on the cycle, it would point to a vertex that does not appear later, contradicting the statement above. Thus, the last outgoing edges of all non-root vertices necessarily form an arborescence.
In the other direction, given any arborescence and an ordering of all the other outgoing edges, we can reconstruct an Eulerian circuit such that applying the construction above to it yields the given arborescence and ordering. Starting from the root , whenever a vertex is reached, choose as the next edge of the Eulerian circuit the earliest unused outgoing edge according to the given ordering at that vertex; if all outgoing edges in the ordering at that vertex have been used, choose the outgoing edge of that vertex in the arborescence as the next edge of the Eulerian circuit. Since the graph is Eulerian, every vertex has equal in-degree and out-degree, so this process cannot terminate at a non-root vertex; the resulting path is therefore a circuit. To prove that the resulting path is a valid Eulerian circuit, it suffices to show that this process traverses every edge.
If it does not, there must be some vertex with an outgoing edge that has not been traversed. Consider vertex . Vertex cannot be the root, because the process eventually terminates at the root, and if the root still had an unused outgoing edge, that would contradict the termination of the process. Thus, is not the root. By the process described above, as long as a non-root vertex has any outgoing edge remaining, its outgoing edge in the arborescence must also remain. Let . Since some incoming edge of has not been traversed, and the out-degree of equals its in-degree, some outgoing edge of must not have been traversed either. We can then examine vertex in the same way. This reasoning moves the vertex under consideration from to , namely one step toward the root along the arborescence. By induction, there must then be an unused outgoing edge of the root . The preceding argument has already shown that this is impossible, giving a contradiction. Therefore, the path obtained in the preceding paragraph is indeed a valid Eulerian circuit.
It can be verified that these maps are injective, and hence they are bijections. The proposition follows.
Implementation
Write the Laplace matrix from the graph, delete one row and one column, and compute the determinant of the resulting matrix. The determinant can be computed using Gaussian elimination.
For example, the number of spanning trees of a square graph is
This can be solved with Gaussian elimination, with time complexity .
Implementation
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
constexpr int MOD = 100000007;
constexpr double eps = 1e-7;
struct matrix {
static constexpr int MAXN = 20;
int n, m;
double mat[MAXN][MAXN];
matrix() { memset(mat, 0, sizeof(mat)); }
void print() {
cout << "MATRIX " << n << " " << m << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << mat[i][j] << "\t";
}
cout << endl;
}
}
void random(int n) {
this->n = n;
this->m = n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) mat[i][j] = rand() % 100;
}
void initSquare() {
this->n = 4;
this->m = 4;
memset(mat, 0, sizeof(mat));
mat[0][1] = mat[0][3] = 1;
mat[1][0] = mat[1][2] = 1;
mat[2][1] = mat[2][3] = 1;
mat[3][0] = mat[3][2] = 1;
mat[0][0] = mat[1][1] = mat[2][2] = mat[3][3] = -2;
this->n--; // remove one row
this->m--; // remove one column
}
double gauss() {
double ans = 1;
for (int i = 0; i < n; i++) {
int sid = -1;
for (int j = i; j < n; j++)
if (abs(mat[j][i]) > eps) {
sid = j;
break;
}
if (sid == -1) continue;
if (sid != i) {
for (int j = 0; j < n; j++) {
swap(mat[sid][j], mat[i][j]);
ans = -ans;
}
}
for (int j = i + 1; j < n; j++) {
double ratio = mat[j][i] / mat[i][i];
for (int k = 0; k < n; k++) {
mat[j][k] -= mat[i][k] * ratio;
}
}
}
for (int i = 0; i < n; i++) ans *= mat[i][i];
return abs(ans);
}
};
int main() {
srand(1);
matrix T;
// T.random(2);
T.initSquare();
T.print();
double ans = T.gauss();
T.print();
cout << ans << endl;
}
Examples
Example 1: 「HEOI2015」Z's Room
Solution This is a basic application of the matrix-tree theorem. Treat each empty room as a node, build the graph according to the input, obtain the Laplace matrix, then delete from row and column , and compute the determinant of the resulting minor. The determinant is computed by using Gaussian elimination to reduce the matrix to upper triangular form and then taking the product of the diagonal entries. In addition, this problem requires Gaussian elimination over the integer subring modulo , ; the Euclidean algorithm can be used.
Example 2: 「FJOI2007」Whirling Virus
Solution There are many solutions to this problem, and using the matrix-tree theorem is the most direct. When the input is , it is easy to write its Laplace matrix of order as:
It suffices to compute the determinant of its order- minor; the only remaining issue is high-precision computation.
Example 2+
Strengthen the data of Example 2 by requiring , while the answer is taken modulo 1000007. (Solving this problem requires some linear algebra knowledge.)
Solution After deriving the recurrence, it can be computed using matrix exponentiation.
The derivation of the recurrence is as follows:
Notice that after deleting the first row and first column of , the resulting matrix has a very regular form, so we are actually computing the determinant of
Expanding the determinant of along its first column gives
Denote the determinants of the three matrices above by , respectively.
Notice that is a tridiagonal determinant; by a similar expansion, we obtain that satisfies the recurrence . Similarly, expanding gives and .
Substituting these recurrences into the expression above gives:
We can therefore conjecture that also satisfies a nonhomogeneous second-order linear recurrence. Using the method of undetermined coefficients, the final recurrence is
Rewriting it as and then using matrix exponentiation yields the answer.
Example 3: 「BZOJ3659」WHICH DREAMED IT
Solution This problem is a direct application of the BEST theorem. However, note that because the problem specifies that 「two ways of completing the task are considered different if and only if the order of using the keys is different」, for every Eulerian circuit, room 1 may start along any outgoing edge, so the answer must also be multiplied by the out-degree of room 1.
Example 4: 「United Provincial Selection 2020 A」The Assignment Problem
Solution First, Möbius inversion is needed to transform the problem into computing the sum of the edge weights of all spanning trees; this is omitted because it is not closely related to this article.
Write the terms of the determinant as . The final answer is the coefficient of the first-degree term of the determinant, because the answer is actually the number of spanning trees after designating one edge the sum of the weight of that edge, so the edge whose weight contributes to the first-degree coefficient is the designated edge. Terms of degree higher than one can be ignored, giving complexity .
「Beijing Provincial Selection Training 2019」Counting Spanning Trees is a more general case: to compute the sum of the -th powers of the sums of spanning-tree weights, construct the terms of the determinant in a similar way; see the Luogu solution for details.
Example 5: AGC051D C4
Solution Counting Eulerian circuits in an undirected graph is an NPC problem, but the graph in this problem is relatively simple. Once the number of edges among the edges directed from to is determined, the orientations of the other three types of edges are determined, and the BEST theorem directly gives a solution with complexity .