-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmst.js
More file actions
72 lines (63 loc) · 1.69 KB
/
mst.js
File metadata and controls
72 lines (63 loc) · 1.69 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
if (typeof window === 'undefined') {
graph = require(__dirname + '/graph.js');
wg = require(__dirname + '/weighted_graph.js');
gs = require(__dirname + '/../chapter2/generic_search.js');
util = require(__dirname + '/../util.js');
}
function totalWeight(wp) {
let result = 0;
for (let edge of wp) {
result += parseInt(edge.weight);
}
return result;
}
function getMst(wGraph, start) {
if (start == null) {
start = 0;
}
if (start > wGraph.vertexCount() - 1 || start < 0) {
return null;
}
let result = [];
let pq = new gs.PriorityQueue();
let visited = []; // where we've been
for (let i = 0; i < wGraph.vertexCount(); i++) {
visited.push(false);
}
function visit(index) {
visited[index] = true;
for (let edge of wGraph.edgesForIndex(index)) {
// add all edges coming from here to pq
if (!visited[edge.v]) {
pq.push(edge);
}
}
}
visit(start); // the first vertex is where everything begins
while (!pq.empty()) { // keep going while there are edges to process
let edge = pq.pop();
if (visited[edge.v]) {
continue; // don't ever revisit
}
// this is the current smallest, so add it to solution
result.push(edge);
visit(edge.v); // visit where this connects
}
return result;
}
function printWeightedPath(wGraph, wp) {
for (let edge of wp) {
util.out(wGraph.vertexAt(edge.u) + ' ' + edge.weight + '> ' + wGraph.vertexAt(edge.v));
}
util.out("Total Weight: " + totalWeight(wp));
}
let _mstExports = {
totalWeight: totalWeight,
getMst: getMst,
printWeightedPath: printWeightedPath
};
if (typeof window === 'undefined') {
module.exports = _mstExports;
} else {
mst = _mstExports;
}