-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathMinimum Spanning Trees.js
40 lines (31 loc) · 1.1 KB
/
Minimum Spanning Trees.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
class Graph {
let ADDED, DISTANCES, PARENTS;
prim(startVertex) {
ADDED = new Array(this.vertices.length).fill(false);
DISTANCES = new Array(this.vertices.length).fill(Number.POSITIVE_INFINITY);
PARENTS = new Array(this.vertices.length).fill(-1);
DISTANCES[startVertex] = 0;
let currentVertex = startVertex, currentEdge;
while (!ADDED[currentVertex]) {
ADDED[currentVertex] = true;
currentEdge = this.connections[currentVertex];
while (currentEdge) {
let nextVertex = currentEdge.adjacencyInfo;
let weight = currentEdge.weight;
if (DISTANCES[nextVertex] > weight && !ADDED[nextVertex]) {
DISTANCES[nextVertex] = weight;
PARENTS[nextVertex] = currentVertex;
}
currentEdge = currentEdge.nextVertex;
}
currentVertex = 1;
let bestCurrentDistance = Number.POSITIVE_INFINITY;
for (let i = 0; i < this.vertices.length; i++) {
if (!ADDED[i] && bestCurrentDistance > DISTANCES[i]) {
bestCurrentDistance = DISTANCES[i];
currentVertex = i;
}
}
}
}
}