Working with Graphs & Trees
Which minimum spanning tree algorithm is implemented here?
function minSpanningTree(graph) {
const edges = [];
for (let vertex in graph) {
for (let neighbor in graph[vertex]) {
edges.push({
from: vertex,
to: neighbor,
weight: graph[vertex][neighbor]
});
}
}
edges.sort((a, b) => a.weight - b.weight);
const disjointSet = new DisjointSet();
const mst = [];
// Initialize disjointSet with all vertices
for (let vertex in graph) {
disjointSet.makeSet(vertex);
}
for (let edge of edges) {
if (disjointSet.find(edge.from) !== disjointSet.find(edge.to)) {
mst.push(edge);
disjointSet.union(edge.from, edge.to);
}
}
return mst;
}