Given a connected undirected graph with v vertices and its adjacency matrix representation, determine the total number of spanning trees that can be formed from the graph.
A spanning tree is a subgraph that connects all vertices of a graph with exactly v-1 edges and contains no cycles.
Output: 3 Explanation: The graph has one cycle among nodes 0, 1, and 2, so removing one edge forms a spanning tree. Since the cycle has 3 edges, removing any one gives 3 possible spanning trees.
Kirchhoff’s Theorem works by converting the graph into a matrix form that captures how nodes are connected. This matrix (called the Laplacian matrix) represents the structure of the graph, and its determinant (cofactor) gives the total number of spanning trees.
Convert the adjacency matrix into the Laplacian matrix which is achieved using the following steps.
A Laplacian matrix L, where
Replace all the diagonal elements with the degree of nodes. For eg. element at (1, 1) position of adjacency matrix will be replaced by the degree of node 1, element, i,e., L[i][i] = degree of node i
Replace all non-diagonal 1's with -1. L[i][j] = -1 if there is an edge between i and j, L[i][j] remains 0 otherwise
Remove any one row and one column from the Laplacian matrix. For example, remove the first row and first column. The cofactor value is the same for any row and column removed, so you can choose any.
Find the determinant (cofactor) of the resulting matrix. This value gives the total number of spanning trees "3". The determinant remains the same regardless of which row and column are removed.
Cayley’s formula for Complete Graph : Itis a special case of Kirchhoff’s theorem because, in a complete graph of n nodes, the determinant is equal to n^(n-2).
It works here because the Laplacian matrix represents how all nodes in the graph are connected. The determinant expands into all possible edge combinations, and due to its mathematical properties, invalid ones (cycles or disconnected) cancel out. As a result, only valid spanning trees remain, so the determinant directly gives their total count.
Output
16
Time Complexity: O(n^3) due to Gaussian elimination for determinant. Auxiliary Space : O(n^2) for storing matrices.