在JavaScript中,求取最小生成树(Minimum Spanning Tree, MST)最常用的算法是Prim算法和Kruskal算法。这里我将提供一个基于Kruskal算法的JavaScript实现。
首先,定义一个用于存储图的数据结构,这里使用JavaScript的类来实现:
class Graph {
constructor(vertices) {
this.V = vertices;
this.graph = [];
}
addEdge(u, v, w) {
this.graph.push([u, v, w]);
}
kruskalMST() {
let result = [];
this.graph = this.graph.sort((a, b) => a[2] - b[2]);
let parent = Array(this.V).fill(0);
let rank = Array(this.V).fill(0);
for (let i = 0; i < this.V; i++) {
parent[i] = i;
rank[i] = 0;
}
let e = 0;
for (let i = 0; i < this.graph.length; i++) {
let u = this.graph[i][0];
let v = this.graph[i][1];
let w = this.graph[i][2];
let x = this.find(parent, u);
let y = this.find(parent, v);
if (x !== y) {
e++;
result.push([u, v, w]);
this.union(parent, rank, x, y);
}
}
return result;
}
find(parent, i) {
if (parent[i] === i) {
return i;
}
return this.find(parent, parent[i]);
}
union(parent, rank, x, y) {
let xroot = this.find(parent, x);
let yroot = this.find(parent, y);
if (rank[xroot] < rank[yroot]) {
parent[xroot] = yroot;
} else if (rank[xroot] > rank[yroot]) {
parent[yroot] = xroot;
} else {
parent[yroot] = xroot;
rank[xroot]++;
}
}
}
然后,你可以像下面这样使用这个类来创建一个图并求出其最小生成树:
let g = new Graph(4);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 6);
g.addEdge(0, 3, 5);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
let result = g.kruskalMST();
console.log("Edges in the constructed MST");
for (let i = 0; i < result.length; i++) {
let u = result[i][0];
let v = result[i][1];
let weight = result[i][2];
console.log(`${u} -- ${v} == ${weight}`);
}