Given a connected, undirected, weighted graph with V
vertices and E
edges, the goal is to compute the sum of the edge weights of the Minimum Spanning Tree (MST). The MST is a subset of the edges that connects all vertices together, without any cycles, and with the minimum total edge weight.
Kruskal's Algorithm - Visualization
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>
// Disjoint Set Union (Union-Find) implementation
typedef struct {
int *parent;
int *rank;
int size;
} DisjointSet;
DisjointSet *createDisjointSet(int n) {
DisjointSet *ds = (DisjointSet *)malloc(sizeof(DisjointSet));
ds->parent = (int *)malloc(n * sizeof(int));
ds->rank = (int *)calloc(n, sizeof(int));
ds->size = n;
for (int i = 0; i < n; i++) {
ds->parent[i] = i;
}
return ds;
}
int findParent(DisjointSet *ds, int u) {
if (ds->parent[u] != u) {
ds->parent[u] = findParent(ds, ds->parent[u]);
}
return ds->parent[u];
}
int unionSets(DisjointSet *ds, int u, int v) {
int pu = findParent(ds, u);
int pv = findParent(ds, v);
if (pu == pv) return 0;
if (ds->rank[pu] < ds->rank[pv]) {
ds->parent[pu] = pv;
} else if (ds->rank[pu] > ds->rank[pv]) {
ds->parent[pv] = pu;
} else {
ds->parent[pv] = pu;
ds->rank[pu]++;
}
return 1;
}
// Edge structure
typedef struct {
int u, v, weight;
} Edge;
int compareEdges(const void *a, const void *b) {
Edge *ea = (Edge *)a;
Edge *eb = (Edge *)b;
return ea->weight - eb->weight;
}
int kruskalMST(int V, Edge edges[], int E) {
qsort(edges, E, sizeof(Edge), compareEdges);
DisjointSet *ds = createDisjointSet(V);
int mstWeight = 0;
int edgeCount = 0;
for (int i = 0; i < E; i++) {
if (unionSets(ds, edges[i].u, edges[i].v)) {
mstWeight += edges[i].weight;
edgeCount++;
if (edgeCount == V - 1) break;
}
}
free(ds->parent);
free(ds->rank);
free(ds);
return mstWeight;
}
int main() {
int V = 4;
Edge edges[] = {
{0, 1, 1},
{0, 2, 3},
{1, 2, 1},
{1, 3, 4},
{2, 3, 2}
};
int E = sizeof(edges) / sizeof(edges[0]);
int result = kruskalMST(V, edges, E);
printf("MST weight: %d\n", result); // Output: 4
return 0;
}
Comments
Loading comments...