⬅ Previous Topic
Find the City With the Fewest Reachable NeighboursNext Topic ⮕
Prim's Algorithm for Minimum Spanning Tree⬅ Previous Topic
Find the City With the Fewest Reachable NeighboursNext Topic ⮕
Prim's Algorithm for Minimum Spanning TreeTopic Contents
A Minimum Spanning Tree (MST) is a subset of the edges of a connected, undirected, and weighted graph that connects all the vertices with the minimum total edge weight and without any cycles.
The MST ensures that:
MSTs are used in various applications like network design (telephone, electrical, or computer networks), clustering, and approximations of NP-hard problems.
V - 1
edges, where V
is the number of vertices.class UnionFind {
constructor(size) {
this.parent = Array.from({ length: size }, (_, i) => i);
}
find(x) {
if (this.parent[x] !== x) this.parent[x] = this.find(this.parent[x]);
return this.parent[x];
}
union(x, y) {
const rootX = this.find(x);
const rootY = this.find(y);
if (rootX === rootY) return false;
this.parent[rootY] = rootX;
return true;
}
}
function kruskalMST(V, edges) {
edges.sort((a, b) => a[2] - b[2]); // Sort edges by weight
const uf = new UnionFind(V);
const mst = [];
let totalWeight = 0;
for (const [u, v, w] of edges) {
if (uf.union(u, v)) {
mst.push([u, v]);
totalWeight += w;
}
}
return { totalWeight, mst };
}
const edges = [
[0, 1, 10], [0, 2, 6], [0, 3, 5], [1, 3, 15], [2, 3, 4]
];
const V = 4;
console.log("Kruskal MST:", kruskalMST(V, edges));
⬅ Previous Topic
Find the City With the Fewest Reachable NeighboursNext Topic ⮕
Prim's Algorithm for Minimum Spanning TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.