learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Matrix-Tree Theorem

One determinant counts every spanning tree

Counts the spanning trees of a graph as a determinant: build the Laplacian, remove one row and column, and eliminate exactly

Time: O(n³)
Space: O(n²)
Use Case: Counting spanning trees, network reliability, electrical circuits
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Kirchhoff's Matrix-Tree Theorem

A spanning tree of a connected graph is a set of edges that connects all the vertices without forming a cycle. A graph usually has many of them, often an astronomical number, and Kirchhoff's matrix-tree theorem counts them exactly with linear algebra. Build the Laplacian matrix L = D − A, with each vertex's degree on the diagonal and −1 for every edge between two vertices off it. Remove any one row and the matching column. The determinant of what is left is the number of spanning trees. Gustav Kirchhoff found this in 1847 while studying electrical networks, and it is one of the first results of algebraic graph theory.

How it works

The visualizer fills the Laplacian in two steps: first the degrees on the diagonal, then −1 for each edge, so every row adds up to zero. That is why the full Laplacian has determinant 0 and the theorem removes a row and a column first, here those of the first vertex. The determinant of the remaining (n − 1) × (n − 1) matrix is computed by Bareiss elimination, a fraction-free variant of Gaussian elimination: each new entry is (a[i][j] · pivot − a[i][p] · a[p][j]) divided by the previous pivot, and the division is always exact, so the numbers stay integers and the count is exact. A zero pivot means swapping rows, which flips the sign, and if no row can be swapped in, the determinant is 0 and the graph is disconnected. The last pivot is the determinant, the number of spanning trees. When there are few enough, the visualizer then lists them one by one on the canvas to check the count. The whole computation takes O(n³) arithmetic operations.

Applications

Counting spanning trees measures how robustly a network is connected: a network with more spanning trees has more ways to stay connected when links fail, so the count appears in network reliability and in the design of communication networks. In electrical engineering, Kirchhoff's original setting, the cofactors of the Laplacian give effective resistances between nodes. Random spanning trees, sampled with the same matrix tools, are used in graph sparsification and in physics models. The Laplacian itself is the central object of spectral graph theory, behind spectral clustering, graph neural networks and diffusion on graphs. For complete graphs the theorem gives Cayley's formula, n^(n − 2) trees on n labelled vertices.

Pseudocode

Build the Laplacian, delete one row and column, and compute the determinant exactly with integer arithmetic.

CountSpanningTrees(G):
    L = n × n zero matrix
    for each vertex v: L[v][v] = degree(v)
    for each edge u–v: L[u][v] -= 1, L[v][u] -= 1
    M = L without the row and column of one vertex
    prev = 1
    for p = 1 .. n - 2:              // Bareiss elimination
        if M[p][p] == 0: swap in a row below (or return 0)
        for i, j > p:
            M[i][j] = (M[i][j] × M[p][p] - M[i][p] × M[p][j]) / prev
        prev = M[p][p]
    return M[n-1][n-1]               // with the sign of the swaps

Bareiss' division is always exact, so every intermediate entry is an integer (a minor of the matrix). Ordinary Gaussian elimination with fractions or floating point would also work, but rounding errors make large counts unreliable.

Worked example, step by step

Count the spanning trees of the house loaded here.

Example graph: Five vertices: a square A, B, D, C (edges A-B, B-D, D-C, C-A) with a roof E joined to A and B. Six edges, so each spanning tree keeps four of them.

  1. Degrees. A and B have degree 3, C, D and E degree 2. These are the diagonal entries of the Laplacian.
  2. Laplacian. Each edge puts −1 in two places. Row A reads 3, −1, −1, 0, −1 for A, B, C, D, E: degree 3, and neighbours B, C and E. Every row sums to 0.
  3. Remove A. Deleting the row and column of A leaves the 4 × 4 matrix for B, C, D, E: rows (3, 0, −1, −1), (0, 2, −1, 0), (−1, −1, 2, 0), (−1, 0, 0, 2).
  4. Elimination. The pivots are 3, then 6, then 7. Each step divides by the previous pivot exactly, and the last diagonal entry comes out as 11.
  5. Listing. The visualizer then shows all 11 trees one by one. Each drops two of the six edges, taken from two different paths between A and B, so that no cycle is left.

11 spanning trees, from the determinant and from the list. The count can be checked by hand: A and B are joined by three paths of lengths 1 (the edge), 2 (through E) and 3 (round the square), and such a graph has 1·2 + 2·3 + 3·1 = 11 spanning trees.

Complexity, and where it comes from

Time: O(n³) arithmetic operations · Space: O(n²)

Building the Laplacian is O(n² + m). Elimination on the (n − 1) × (n − 1) matrix updates O(n²) entries for each of n − 2 pivots, O(n³) operations. With Bareiss every intermediate number is a minor, so its size stays polynomial in n and in the bit length of the entries. Listing the trees is a different matter: there can be n^(n − 2) of them, which is why the visualizer lists them only when there are few.

When to use Kirchhoff's Matrix-Tree Theorem, and when not to

Counting spanning trees, finding one, and finding the cheapest one are different problems.

AlternativePrefer it whenCost
Enumerate all subsets of n − 1 edgesVery small graphs, or when the trees themselves are needed.C(m, n − 1) checks
Kruskal or PrimOne spanning tree of minimum total weight, not the count.O(m log n)
Eigenvalues of the LaplacianThe same count as the product of the non-zero eigenvalues divided by n. Useful in theory and for structured graphs, not for exact integers.O(n³), floating point

Common pitfalls

  • Taking the determinant of the full Laplacian. Its rows add up to zero, so its determinant is always 0. One row and the matching column must be removed first.
  • Floating-point elimination. Counts grow fast, and ordinary elimination with doubles rounds them. Use exact integers (Bareiss, or fractions) or work modulo a prime when only the count modulo p is needed.
  • Ignoring parallel edges or loops. Parallel edges are counted with multiplicity: two edges between u and v give −2 and add 2 to the degrees. A loop never belongs to a tree and must be left out of the degrees too.

Frequently asked questions

What does the matrix-tree theorem say?
For a connected graph, every cofactor of the Laplacian matrix L = D − A equals the number of spanning trees. Delete any one row and the same column, and the determinant of the rest is the count.
How many spanning trees does a complete graph have?
K_n has n^(n − 2), Cayley's formula. It follows from the matrix-tree theorem, and Prüfer codes give a direct bijection.
Does it work for weighted graphs?
With weights in the Laplacian (weighted degrees, minus weights off the diagonal), the cofactor is the sum over all spanning trees of the product of their edge weights. With all weights 1 that is the plain count.
What about directed graphs?
Tutte's version counts arborescences, spanning trees with all edges directed away from (or towards) a root, using the in-degree or out-degree Laplacian.

Related algorithms: Kruskal's MST Algorithm, Prim's MST Algorithm, Prüfer Code, Borůvka's Algorithm, Connected Components

An example graph: you can change it, or start blank.

Zoom Controls

59%
Nodes: 5
Edges: 6