Published
Edited
Dec 30, 2021
3 stars
Insert cell
# Minimum Spanning Tree
Insert cell
function find(parent, x) {
if (parent[x] === x) return x;
return (parent[x] = find(parent, parent[x]));
}
Insert cell
function union(parent, a, b) {
a = find(parent, a);
b = find(parent, b);
if (a < b) {
parent[b] = a;
} else {
parent[a] = b;
}
}
Insert cell
function compare(parent, a, b) {
a = find(parent, a);
b = find(parent, b);
return a === b;
}
Insert cell
function solution(n, costs) {
let mininumCost = 0;
const sortedCosts = costs.sort((a, b) => a[2] - b[2]);
const parent = Array.from({ length: n }, (_, i) => i);

for (const [a, b, cost] of sortedCosts) {
if (!compare(parent, a, b)) {
mininumCost += cost;
union(parent, a, b);
}
}

return mininumCost;
}
Insert cell
solution(4, [
[0, 1, 1],
[0, 2, 2],
[1, 2, 5],
[1, 3, 1],
[2, 3, 8]
])
Insert cell
FileAttachment("image.png").image()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more