C Program to Implement Minimum Spanning Tree
Last Updated :
24 May, 2024
A Minimum Spanning Tree is a subset of edges from a undirected graph that connects all vertices with minimum total weight and contains no cycle. The most common algorithms to generate Minimum Spanning Tree are Kruskal's algorithm and Prim's algorithm. In this article we explain about implement Minimum Spanning Tree with Kruskal's algorithm. You can also use Prim's algorithm based on your requirement.
What is Minimum Spanning Tree in C?
Minimum Spanning Tree in C can be represented in different ways, depending on the algorithm used. Here we use Kruskal's Algorithm to Implement Minimum Spanning Tree.
- Begins with all edges sorted by weight and iterates through them, adding an edge to the Minimum Spanning Tree if it does not create a cycle.
- And Requires an edge list and a Disjoint Set Union structure to track connected components in the graph.
Minimum Spanning Tree has V-1 edges where V is the number of vertices in Graph.
Example
Here we take one example to explain how Implement Minimum Spanning Tree by using the Kruskal's algorithm by calculating minimum total weights without a cycle.
MSTExplanation
The graph has 4 vertices (0, 1, 2, 3) and 5 edges with the following weights
- Edge from vertex 0 to 1 with a weight of 10.
- Edge from vertex 0 to 2 with a weight of 6.
- Edge from vertex 0 to 3 with a weight of 5.
- Edge from vertex 1 to 3 with a weight of 15.
- Edge from vertex 2 to 3 with a weight of 4.
Minimum Spanning Tree of the Above Graph
Kruskal's algorithm sorts the edges by weight, then iterates through the edges to include them in the MST if they don't create a cycle.
- Edge from vertex 2 to 3 with a weight of 4
- Edge from vertex 0 to 3 with a weight of 5
- Edge from vertex 0 to 1 with a weight of 10
These edges connect all four vertices without creating cycles, forming the Minimum Spanning Tree with the minimum total weight 19.
C Program to Implement Minimum Spanning Tree
C
#include <stdio.h>
#include <stdlib.h>
// Structure to represent an edge with source, destination, and weight
typedef struct Edge {
int src;
int dest;
int weight;
} Edge;
// Structure to represent a graph with vertices, edges, and an array of edges
typedef struct Graph {
int V;
int E;
Edge* edges;
} Graph;
// Create a new graph with V vertices and E edges
Graph* createGraph(int V, int E) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->E = E;
graph->edges = (Edge*)malloc(E * sizeof(Edge));
return graph;
}
// Disjoint Set Union (DSU) structure with parent and rank
typedef struct DSU {
int* parent;
int* rank;
} DSU;
// Create a new DSU with V vertices
DSU* createDSU(int V) {
DSU* dsu = (DSU*)malloc(sizeof(DSU));
dsu->parent = (int*)malloc(V * sizeof(int));
dsu->rank = (int*)malloc(V * sizeof(int));
for (int i = 0; i < V; i++) {
dsu->parent[i] = i;
dsu->rank[i] = 0;
}
return dsu;
}
// Find the representative (root) of a set with path compression
int find(DSU* dsu, int x) {
if (dsu->parent[x] != x) {
dsu->parent[x] = find(dsu, dsu->parent[x]);
}
return dsu->parent[x];
}
// Union two sets by rank
void unionSets(DSU* dsu, int x, int y) {
int rootX = find(dsu, x);
int rootY = find(dsu, y);
if (rootX != rootY) {
if (dsu->rank[rootX] < dsu->rank[rootY]) {
dsu->parent[rootX] = rootY;
} else if (dsu->rank[rootX] > dsu->rank[rootY]) {
dsu->parent[rootY] = rootX;
} else {
dsu->parent[rootY] = rootX;
dsu->rank[rootX]++;
}
}
}
// Compare function for sorting edges by weight
int compareEdges(const void* a, const void* b) {
Edge* edgeA = (Edge*)a;
Edge* edgeB = (Edge*)b;
return edgeA->weight - edgeB->weight;
}
// Kruskal's algorithm to find the Minimum Spanning Tree
void kruskalMST(Graph* graph) {
// Step 1: Sort the edges by weight
qsort(graph->edges, graph->E, sizeof(Edge), compareEdges);
DSU* dsu = createDSU(graph->V);
Edge* result = (Edge*)malloc((graph->V - 1) * sizeof(Edge));
int edgeCount = 0;
int i = 0;
while (edgeCount < graph->V - 1 && i < graph->E) {
Edge nextEdge = graph->edges[i++];
int srcRoot = find(dsu, nextEdge.src);
int destRoot = find(dsu, nextEdge.dest);
if (srcRoot != destRoot) {
result[edgeCount++] = nextEdge;
unionSets(dsu, srcRoot, destRoot);
}
}
printf("Edges in the Minimum Spanning Tree:\n");
for (int j = 0; j < edgeCount; j++) {
printf("%d -- %d : %d\n", result[j].src, result[j].dest, result[j].weight);
}
free(result);
free(dsu->parent);
free(dsu->rank);
free(dsu);
}
int main() {
int V = 4; // Number of vertices
int E = 5; // Number of edges
Graph* graph = createGraph(V, E);
// Edges: (src, dest, weight)
graph->edges[0].src = 0;
graph->edges[0].dest = 1;
graph->edges[0].weight = 10;
graph->edges[1].src = 0;
graph->edges[1].dest = 2;
graph->edges[1].weight = 6;
graph->edges[2].src = 0;
graph->edges[2].dest = 3;
graph->edges[2].weight = 5;
graph->edges[3].src = 1;
graph->edges[3].dest = 3;
graph->edges[3].weight = 15;
graph->edges[4].src = 2;
graph->edges[4].dest = 3;
graph->edges[4].weight = 4;
kruskalMST(graph);
free(graph->edges);
free(graph);
return 0;
}
OutputEdges in the Minimum Spanning Tree:
2 -- 3 : 4
0 -- 3 : 5
0 -- 1 : 10
Time Complexity: O(nlog n)
Space Complexity: O(n)
Applications of MST
- In Networking design mostly The Minimum Spanning Tree is used
- For identifying natural clustering in Graph .
- Used in approximation algorithms for problems like Travelling Salesman Problem.
- Constructing efficient road or pipelines network with minimal construction costs.
Conclusion
Prim's Algorithms is an effective for creating or implementing Minimum Spanning Tree. Kruskal's Algorithm is typically chosen when edges are already given, and sorting them is efficient. It offers time and space complexity that is well suited for large scale graphs with applications in network designing, clustering, And other optimization problems.
Similar Reads
C++ Program to Implement Minimum Spanning Tree Given a weighted graph, the objective is to find a subset of edges that forms a tree including every vertex, where the total weight of all the edges in the tree is minimized. In this article, we will explore various algorithms through which we can implement a Minimum Spanning Tree in C++.What is Min
7 min read
Java Program to Implement Minimum Spanning Tree A Minimum Spanning Tree (MST) is a fundamental concept in graph theory and computer science particularly in the field of network optimization. It represents the minimum set of edges required to connect all the vertices in the graph without forming any cycles and with the minimum possible total edge
4 min read
C++ Program to Implement B+ Tree A B+ Tree is an advanced data structure that extends the B-tree by adding a linked list of leaf nodes. This structure is widely used in databases and file systems to allow efficient insertion, deletion, and search operations. In this article, we will learn how to implement the B+ Tree in C++ along w
10 min read
C Program to Implement AVL Tree In C, AVL trees are self-balancing binary search trees. They maintain a balance by ensuring that the difference between the heights of their left subtrees and the right subtrees can be either 0, 1 or -1 and whenever this height property is violated, the tree balances itself using the different rotat
8 min read
C++ Program to Implement AVL Tree AVL Tree, named after its inventors Adelson-Velsky and Landis, is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one, which ensures that the tree remains approximately balanced, providing efficient search, insertion, and delet
11 min read