-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
49 lines (40 loc) · 1.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
var DisjointSet = require('ngraph.disjoint-set');
module.exports = kruskal;
function kruskal(graph, getWeight) {
var tree = [];
getWeight = getWeight || uniformWeight;
// map of disjoint sets for quick lookup
var nodes = new Map();
// Sorted array of edges by their weight
var links = [];
graph.forEachNode(initSet);
graph.forEachLink(initLink);
links.sort(byWeight);
for (var i = 0; i < links.length; ++i) {
var fromId = links[i].fromId;
var toId = links[i].toId;
var fromSet = nodes.get(fromId);
var toSet = nodes.get(toId);
if (fromSet.find() !== toSet.find()) {
tree.push(new TreeNode(fromId, toId));
fromSet.union(toSet);
}
}
return tree;
function initLink(link) {
links.push(link);
}
function initSet(node) {
nodes.set(node.id, new DisjointSet(node.id));
}
function byWeight(x, y) {
return getWeight(x) - getWeight(y);
}
}
function uniformWeight(link) {
return 1;
}
function TreeNode(fromId, toId) {
this.fromId = fromId;
this.toId = toId;
}