Welcome to this comprehensive guide on the Minimum Spanning Tree (MST) in C programming! This lesson is designed for both beginners and intermediates, so let's dive right in. 📝
A Minimum Spanning Tree (MST) is a subset of the edges of a connected, undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.
In other words, an MST is a tree that spans the entire graph, where the sum of the weights of the edges in the tree is the smallest possible among all such trees.
MSTs are essential in various real-world applications such as network design, circuit layout, and transportation systems. They help in finding the least-cost network that connects a set of nodes, making them an integral part of algorithmic problem-solving.
We will be discussing the Kruskal's Algorithm, a popular and efficient method for finding the Minimum Spanning Tree. Let's understand the process:
Now, let's write a C program to implement Kruskal's Algorithm:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct Node {
int vertex;
struct Node* next;
}* AdjList;
AdjList list[MAX];
int visited[MAX];
void makeSet(int i) {
list[i] = (AdjList)malloc(sizeof(struct Node));
list[i]->vertex = i;
list[i]->next = NULL;
visited[i] = 0;
}
void unionSet(int x, int y) {
AdjList temp = list[x];
temp->next = list[y];
list[x] = temp;
visited[y] = visited[x];
}
void addEdge(int x, int y, int weight) {
AdjList newNode = (AdjList)malloc(sizeof(struct Node));
newNode->vertex = y;
newNode->next = list[x];
list[x] = newNode;
}
void printMST(AdjList root) {
printf("%d -> ", root->vertex);
AdjList temp = root->next;
while (temp != NULL) {
printMST(temp);
printf("%d -> ", temp->vertex);
temp = temp->next;
}
}
void kruskalMST(int vertices) {
int e, i, min, u, v;
AdjList temp;
for (i = 0; i < vertices; i++)
makeSet(i);
e = 0;
while (e < vertices - 1) {
min = 32767;
for (i = 0; i < vertices; i++) {
if (!visited[i]) {
temp = list[i];
while (temp != NULL) {
if (!visited[temp->vertex]) {
if (temp->vertex < min) {
min = temp->vertex;
u = i;
v = temp->vertex;
}
}
temp = temp->next;
}
}
}
visited[u] = visited[v] = 1;
addEdge(u, v, 0);
e++;
printf("\nEdge (%d, %d) with weight 0 added to MST\n", u, v);
}
printf("\nMinimum Spanning Tree:\n");
temp = list[0];
printMST(temp);
printf("\n");
}
int main() {
int vertices, edges;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
printf("Enter the number of edges: ");
scanf("%d", &edges);
for (int i = 0; i < vertices; i++)
makeSet(i);
int u, v, w;
for (int i = 0; i < edges; i++) {
scanf("%d %d %d", &u, &v, &w);
addEdge(u, v, w);
}
kruskalMST(vertices);
return 0;
}What is the main goal of finding the Minimum Spanning Tree in a graph?
This C program demonstrates Kruskal's Algorithm for finding the Minimum Spanning Tree in a graph. It is practical, easy to understand, and relevant to real-world projects. Happy learning! 🎉