-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.js
91 lines (79 loc) · 1.95 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
function solve(graph, s) {
var solutions = {};
solutions[s] = [];
solutions[s].dist = 0;
while(true) {
var parent = null;
var nearest = null;
var dist = Infinity;
//for each existing solution
for(var n in solutions) {
if(!solutions[n])
continue
var ndist = solutions[n].dist;
var adj = graph[n];
//for each of its adjacent nodes...
for(var a in adj) {
//without a solution already...
if(solutions[a])
continue;
//choose nearest node with lowest *total* cost
var d = adj[a] + ndist;
if(d < dist) {
//reference parent
parent = solutions[n];
nearest = a;
dist = d;
}
}
}
//no more solutions
if(dist === Infinity) {
break;
}
//extend parent's solution path
solutions[nearest] = parent.concat(nearest);
//extend parent's cost
solutions[nearest].dist = dist;
}
return solutions;
}
//create graph
var graph = {};
var layout = {
'R': ['2'],
'2': ['3','4'],
'3': ['4','6','13'],
'4': ['5','8'],
'5': ['7','11'],
'6': ['13','15'],
'7': ['10'],
'8': ['11','13'],
'9': ['14'],
'10': [],
'11': ['12'],
'12': [],
'13': ['14'],
'14': [],
'15': []
}
for(var id in layout) {
if(!graph[id])
graph[id] = {};
layout[id].forEach(function(aid) {
graph[id][aid] = 1;
if(!graph[aid])
graph[aid] = {};
graph[aid][id] = 1;
});
}
//choose start node
var start = '10';
//get all solutions
var solutions = solve(graph, start);
console.log("From '"+start+"' to");
//display solutions
for(var s in solutions) {
if(!solutions[s]) continue;
console.log(" -> " + s + ": [" + solutions[s].join(", ") + "] (dist:" + solutions[s].dist + ")");
}