Skip to content

Instantly share code, notes, and snippets.

@jresendiz27
Forked from n8agrin/kruskal.js
Last active August 31, 2021 05:58
Show Gist options
  • Save jresendiz27/01caad02d82e9f6d93e9 to your computer and use it in GitHub Desktop.
Save jresendiz27/01caad02d82e9f6d93e9 to your computer and use it in GitHub Desktop.
// See http://en.wikipedia.org/wiki/Kruskal's_algorithm
// and http://programmingpraxis.com/2010/04/06/minimum-spanning-tree-kruskals-algorithm/
var _ = require('underscore');
var nodes = ["A", "B", "C", "D", "E", "F", "G"];
var edges = [
["A", "B", 7], ["A", "D", 5],
["B", "C", 8], ["B", "D", 9], ["B", "E", 7],
["C", "E", 5],
["D", "E", 15], ["D", "F", 6],
["E", "F", 8], ["E", "G", 9],
["F", "G", 11]
];
function kruskal(nodes, edges) {
var mst = [];
var forest = _.map(nodes, function(node) { return [node]; });
var sortedEdges = _.sortBy(edges, function(edge) { return -edge[2]; });
while(forest.length > 1) {
var edge = sortedEdges.pop();
var n1 = edge[0],
n2 = edge[1];
var t1 = _.filter(forest, function(tree) {
return _.include(tree, n1);
});
var t2 = _.filter(forest, function(tree) {
return _.include(tree, n2);
});
if (t1 != t2) {
forest = _.without(forest, t1[0], t2[0]);
forest.push(_.union(t1[0], t2[0]));
mst.push(edge);
}
}
return mst;
}
console.log(kruskal(nodes, edges));
@AndriyHromyak
Copy link

if (t1 != t2) will always be true since you are comparing arrays, isin't it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment