Total number of Spanning Trees in a Graph
Last Updated :
13 Jul, 2024
If a graph is a complete graph with n vertices, then total number of spanning trees is n(n-2) where n is the number of nodes in the graph. In complete graph, the task is equal to counting different labeled trees with n nodes for which have Cayley’s formula.
What if graph is not complete?
Follow the given procedure:
- STEP 1: Create Adjacency Matrix for the given graph.
- STEP 2: 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 at (2,2) position of adjacency matrix will be replaced by the degree of node 2, and so on.
- STEP 3: Replace all non-diagonal 1’s with -1.
- STEP 4: Calculate co-factor for any element.
- STEP 5: The cofactor that you get is the total number of spanning tree for that graph.
Consider the following graph:
Adjacency Matrix for the above graph will be as follows:

After applying STEP 2 and STEP 3, adjacency matrix will look like
The co-factor for (1, 1) is 8. Hence total no. of spanning tree that can be formed is 8.
NOTE: Co-factor for all the elements will be same. Hence we can compute co-factor for any element of the matrix. This method is also known as Kirchhoff’s Theorem. It can be applied to complete graphs also.
let’s see another example to solve these problems by making use of the Laplacian matrix.
A Laplacian matrix L,
where L[i, i] is the degree of node i and L[i, j] = -1 if there is an edge between nodes i and j, and otherwise L[i, j] = 0.
Kirchhoff’s theorem provides a way to calculate the number of spanning trees for a given graph as a determinant of a special matrix.
consider the following graph,

the undirected graph
All possible spanning trees are as follows

three spanning trees
In order to calculate the number of spanning trees, construct a Laplacian matrix L, where L[i, i] is the degree of node i and L[i, j] = ?1 if there is an edge between nodes i and j, and otherwise L[i, j] = 0.
for the above graph, The Laplacian matrix will look like this
The number of spanning trees equals the determinant of a matrix.
The Determinant of a matrix that can be obtained when we remove any row and any column from L.
For example, if we remove the first row and column, the result will be,
The determinant is always the same, regardless of which row and column we remove from L.
C++
#include<bits/stdc++.h>
using namespace std;
// C++ program to find number of spanning
// trees in a graph using Matrix Multiplication
#define MAX 100
#define MOD 1000000007
// Matrix Multiplication
void multiply(int A[MAX][MAX], int B[MAX][MAX], int C[MAX][MAX])
{
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
for (int k = 0; k < MAX; k++)
C[i][j] = (C[i][j] + (A[i][k] * B[k][j])%MOD)%MOD;
}
// Function to find Nth power of A
void power(int A[MAX][MAX], int N, int result[MAX][MAX])
{
int temp[MAX][MAX];
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
result[i][j] = (i == j);
while (N>0)
{
if (N%2 == 1)
{
multiply(A, result, temp);
for (int i=0; i<MAX; i++)
for (int j=0; j<MAX; j++)
result[i][j] = temp[i][j];
}
N = N/2;
multiply(A, A, temp);
for (int i=0; i<MAX; i++)
for (int j=0; j<MAX; j++)
A[i][j] = temp[i][j];
}
}
// Function to find number of Spanning
// Trees in a Graph using Matrix
// Multiplication.
int numOfSpanningTree(int graph[][MAX], int V)
{
int result[MAX][MAX] = {0};
int temp[MAX][MAX] = {0};
// Create a copy of graph as the
// Adjacency matrix will be changed
// during the process
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
temp[i][j] = graph[i][j];
// Find (V-2)th power of Adjacency
// matrix
power(temp, V-2, result);
int ans = 0;
// Find sum of all elements in (V-2)th
// power
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
ans = (ans + result[i][j])%MOD;
return ans;
}
// Driver program
int main()
{
// Let us create the following graph
// 2 <-> 3
// | |
// 0 <-1-> 1
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
int graph[][MAX] = {
{0, 1, 1, 1},
{1, 0, 1, 1},
{1, 1, 0, 1},
{1, 1, 1, 0}
};
cout << numOfSpanningTree(graph, V);
return 0;
}
Java
// This Java program finds the number of spanning trees in a
// graph using Matrix Multiplication.
import java.util.*;
public class Main {
static final int MAX = 100;
static final int MOD = 1000000007;
// Matrix Multiplication
static void multiply(int A[][], int B[][], int C[][])
{
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
for (int k = 0; k < MAX; k++)
C[i][j] = (int)((C[i][j]
+ (A[i][k] * B[k][j])
% MOD)
% MOD);
}
// Function to find Nth power of A
static void power(int A[][], int N, int result[][])
{
int temp[][] = new int[MAX][MAX];
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
result[i][j] = (i == j) ? 1 : 0;
while (N > 0) {
if (N % 2 == 1) {
multiply(A, result, temp);
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
result[i][j] = temp[i][j];
}
N = N / 2;
multiply(A, A, temp);
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
A[i][j] = temp[i][j];
}
}
// Function to find number of Spanning Trees in a Graph
// using Matrix Multiplication.
static int numOfSpanningTree(int graph[][], int V)
{
int result[][] = new int[MAX][MAX];
int temp[][] = new int[MAX][MAX];
// Create a copy of graph as the Adjacency matrix
// will be changed during the process
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
temp[i][j] = graph[i][j];
// Find (V-2)th power of Adjacency matrix
power(temp, V - 2, result);
int ans = 0;
// Find sum of all elements in (V-2)th power
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
ans = (int)((ans + result[i][j]) % MOD);
return ans;
}
// Driver program
public static void main(String[] args)
{
// Let us create the following graph
// 2 <-> 3
// | |
// 0 <-1-> 1
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
int graph[][] = { { 0, 1, 1, 1 },
{ 1, 0, 1, 1 },
{ 1, 1, 0, 1 },
{ 1, 1, 1, 0 } };
System.out.println(numOfSpanningTree(graph, V));
}
}
Python
# This Python program finds the number of spanning trees in a
# graph using Matrix Multiplication.
MAX = 100
MOD = 1000000007
# Matrix Multiplication
def multiply(A, B, C):
for i in range(MAX):
for j in range(MAX):
C[i][j] = 0
for k in range(MAX):
C[i][j] = (C[i][j] + (A[i][k] * B[k][j]) % MOD) % MOD
# Function to find Nth power of A
def power(A, N, result):
temp = [[0] * MAX for i in range(MAX)]
for i in range(MAX):
for j in range(MAX):
result[i][j] = 1 if i == j else 0
while N > 0:
if N % 2 == 1:
multiply(A, result, temp)
for i in range(MAX):
for j in range(MAX):
result[i][j] = temp[i][j]
N = N // 2
multiply(A, A, temp)
for i in range(MAX):
for j in range(MAX):
A[i][j] = temp[i][j]
# Function to find number of Spanning Trees in a Graph
# using Matrix Multiplication.
def numOfSpanningTree(graph, V):
result = [[0] * MAX for i in range(MAX)]
temp = [[0] * MAX for i in range(MAX)]
# Create a copy of graph as the Adjacency matrix
# will be changed during the process
for i in range(V):
for j in range(V):
temp[i][j] = graph[i][j]
# Find (V-2)th power of Adjacency matrix
power(temp, V - 2, result)
ans = 0
# Find sum of all elements in (V-2)th power
for i in range(V):
for j in range(V):
ans = (ans + result[i][j]) % MOD
return ans
# Driver program
if __name__ == '__main__':
# Let us create the following graph
# 2 <-> 3
# | |
# 0 <-1-> 1
V = 4 # Number of vertices in graph
E = 5 # Number of edges in graph
graph = [[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0]]
print(numOfSpanningTree(graph, V))
C#
// C# program to find number of spanning
// trees in a graph using Matrix Multiplication
using System;
class GFG
{
static int MAX = 100;
static int MOD = 1000000007;
// Matrix Multiplication
static void multiply(int[,] A, int[,] B, int[,] C)
{
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
for (int k = 0; k < MAX; k++)
C[i, j] = (C[i, j] + (A[i, k] * B[k, j]) % MOD) % MOD;
}
// Function to find Nth power of A
static void power(int[,] A, int N, int[,] result)
{
int[,] temp = new int[MAX, MAX];
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
result[i, j] = (i == j) ? 1 : 0;
while (N > 0)
{
if (N % 2 == 1)
{
multiply(A, result, temp);
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
result[i, j] = temp[i, j];
}
N = N / 2;
multiply(A, A, temp);
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
A[i, j] = temp[i, j];
}
}
// Function to find number of Spanning
// Trees in a Graph using Matrix
// Multiplication.
static int numOfSpanningTree(int[,] graph, int V)
{
int[,] result = new int[MAX, MAX];
int[,] temp = new int[MAX, MAX];
// Create a copy of graph as the
// Adjacency matrix will be changed
// during the process
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
temp[i, j] = graph[i, j];
// Find (V-2)th power of Adjacency
// matrix
power(temp, V - 2, result);
int ans = 0;
// Find sum of all elements in (V-2)th
// power
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
ans = (ans + result[i, j]) % MOD;
return ans;
}
// Driver program
public static void Main()
{
// Let us create the following graph
// 2 <-> 3
// | |
// 0 <-1-> 1
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
int[,] graph = {
{0, 1, 1, 1},
{1, 0, 1, 1},
{1, 1, 0, 1},
{1, 1, 1, 0}
};
Console.Write(numOfSpanningTree(graph, V));
}
}
// This code is contributed by NarasingaNikhil
JavaScript
const MAX = 100;
const MOD = 1000000007;
// Matrix Multiplication
function multiply(A, B, C) {
for (let i = 0; i < MAX; i++) {
for (let j = 0; j < MAX; j++) {
C[i][j] = 0;
for (let k = 0; k < MAX; k++) {
C[i][j] = (C[i][j] + (A[i][k] * B[k][j]) % MOD) % MOD;
}
}
}
}
// Function to find Nth power of A
function power(A, N, result) {
let temp = new Array(MAX).fill().map(() => new Array(MAX).fill(0));
for (let i = 0; i < MAX; i++) {
result[i][i] = 1;
}
while (N > 0) {
if (N % 2 == 1) {
multiply(A, result, temp);
for (let i = 0; i < MAX; i++) {
for (let j = 0; j < MAX; j++) {
result[i][j] = temp[i][j];
}
}
}
N = Math.floor(N / 2);
multiply(A, A, temp);
for (let i = 0; i < MAX; i++) {
for (let j = 0; j < MAX; j++) {
A[i][j] = temp[i][j];
}
}
}
}
// Function to find number of Spanning Trees in a Graph
// using Matrix Multiplication.
function numOfSpanningTree(graph, V) {
let result = new Array(MAX).fill().map(() => new Array(MAX).fill(0));
let temp = new Array(MAX).fill().map(() => new Array(MAX).fill(0));
// Create a copy of graph as the Adjacency matrix
// will be changed during the process
for (let i = 0; i < V; i++) {
for (let j = 0; j < V; j++) {
temp[i][j] = graph[i][j];
}
}
// Find (V-2)th power of Adjacency matrix
power(temp, V - 2, result);
let ans = 0;
// Find sum of all elements in (V-2)th power
for (let i = 0; i < V; i++) {
for (let j = 0; j < V; j++) {
ans = (ans + result[i][j]) % MOD;
}
} ans = ans+ans;
return ans;
}
// Driver program
// Let us create the following graph
// 2 <-> 3
// | |
// 0 <-1-> 1
const V = 4; // Number of vertices in graph
const E = 5; // Number of edges in graph
const graph = [[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0]];
console.log(numOfSpanningTree(graph, V));
Time Complexity: The given program uses the Matrix Chain Multiplication algorithm to find the number of spanning trees in a given graph. The algorithm works by computing the (V-2)th power of the adjacency matrix of the graph, where V is the number of vertices in the graph. The number of spanning trees in the graph is equal to the sum of all the entries in the resulting matrix.
The time complexity of the program is determined by the matrix multiplication and exponentiation operations. The matrix multiplication operation takes O(V^3) time, and it is performed N times, where N is the power to which the adjacency matrix is raised. Since N can be as large as V-2, the total time complexity of the program is O(V^3 * log N).
Space Complexity:
The space complexity of the program is determined by the size of the adjacency matrix and the result matrix. Since the matrices are of size VxV, the space complexity of the program is O(V^2). In addition, there are some temporary matrices created during the matrix multiplication and exponentiation operations, but they are of the same size as the input matrices and do not contribute significantly to the space complexity.
Overall, the program is efficient for finding the number of spanning trees in small to medium-sized graphs. However, for large graphs, the time and space complexity of the program may become a bottleneck, and alternative algorithms may be more appropriate.
NOTE:
Cayley’s formula is a special case of Kirchhoff’s theorem because, in a complete graph of n nodes, the determinant is equal to nn-2
Similar Reads
Graph Algorithms
Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
3 min read
Introduction to Graph Data Structure
Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
15+ min read
Graph and its representations
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
12 min read
Types of Graphs with Examples
A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
9 min read
Basic Properties of a Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
4 min read
Applications, Advantages and Disadvantages of Graph
Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
7 min read
Transpose graph
Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
9 min read
Difference Between Graph and Tree
Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. What is Graph?A graph data structure is a collection o
2 min read
BFS and DFS on Graph
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Depth First Search or DFS for a Graph
In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
4 min read
Iterative Depth First Traversal of Graph
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0
15+ min read
BFS for Disconnected Graph
In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
14 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transit
8 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS st
2 min read
Cycle in a Graph
Detect Cycle in a Directed Graph
Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not. Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 0 Input: V = 4, edges[][] = [[0, 1], [0, 2
15+ min read
Detect cycle in an undirected graph
Given an undirected graph, the task is to check if there is a cycle in the given graph. Examples: Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]] Output: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0 Input: V = 4, edges[][] = [[0, 1], [1, 2], [2, 3]] Output: falseExplana
8 min read
Detect Cycle in a directed graph using colors
Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle. Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns tru
9 min read
Detect a negative cycle in a Graph | (Bellman Ford)
Given a directed weighted graph, the task is to find whether the given graph contains any negative-weight cycle or not. Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value. Example: Input: Output: No Input: Output: Yes Algorithm to Find Negative Cycle in a Directe
15+ min read
Cycles of length n in an undirected and connected graph
Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
10 min read
Detecting negative cycle using Floyd Warshall
We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
12 min read
Clone a Directed Acyclic Graph
A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
12 min read