-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDijkstra.js
100 lines (77 loc) · 2.82 KB
/
Dijkstra.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
(function () {
//<summary>
// Dijkstra's algorithm to find shortest path from s to all other nodes
//</summary>
//<params name="graph" type="DirectedGraph"></param>
//<params name="start" type="string"></param>
var Djikstra = function (graph, start) {
this.Graph = graph;
this.visited = new Array(graph.size());
this.distance = new Array(graph.size());
this.preds = [];
this.start = start;
this.initialize();
};
var minVertex = function (distance, visitedNodes) {
var x = MAX_VALUE, y = -1, i;
for (i = 0; i < distance.length; i++) {
if (!visitedNodes[i] && distance[i] < x) {
y = i;
x = distance[i];
}
}
return y;
}
var MAX_VALUE = Number.MAX_VALUE;
Djikstra.prototype = {
distance: [],
//<summary>
// initialize
//</summary>
initialize: function () {
var idxStart = this.Graph.indexOf(this.start), i, j;
for (var i = 0; i < this.Graph.size() ; i++) {
this.distance[i] = Number.MAX_VALUE;
this.visited[i] = false;
this.preds[i] = null;
}
this.distance[idxStart] = 0;
for (i = 0 ; i < this.distance.length; i++) {
var next = minVertex(this.distance, this.visited);
this.visited[next] = true;
// The shortest path to next is dist[next] and via pred[next].
var neighbors = this.Graph.edgesFrom(this.Graph.nodeAt(next));
for (j = 0; j < neighbors.length; j++) {
var neighborlength = Number(neighbors[j][1]) + Number(this.distance[next]);
var neighbor = neighbors[j][0];
var neighborIdx = this.Graph.indexOf(neighbor);
if (this.distance[neighborIdx] > neighborlength) {
this.distance[neighborIdx] = neighborlength;
this.preds[neighborIdx] = next;
}
}
}
return this;
},
//<summary>
// Find the best path between 2 nodes.
//</summary>
bestPath: function (source, destination) {
var path = [];
var end = this.Graph.indexOf(destination);
var idxSource = this.Graph.indexOf(source);
while (end != idxSource) {
path.splice(0, 0, this.Graph.nodeAt(end));
end = this.preds[end];
}
path.splice(0, 0, source);
return path;
},
};
window.Djikstra = Djikstra;
if (typeof define === "function" && define.amd) {
define("Djikstra", [], function () {
return Djikstra;
});
}
})();