Skip to content

Commit cdab9f9

Browse files
authored
Dijkstra Smallest Path
1 parent c98361b commit cdab9f9

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

maths/DijkstraSmallestPath.js

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
function solve(graph, s) {
2+
var solution = {};
3+
solutions[s] = [];
4+
solutions[s].dist = 0;
5+
6+
while(true) {
7+
var parent = null;
8+
var nearest = null;
9+
var dist = Infinity;
10+
11+
12+
for(var n in solutions) {
13+
if(!solutions[n])
14+
continue
15+
var ndist = solutions[n].dist;
16+
var adj = graph[n];
17+
//for each of its adjacent nodes...
18+
for(var a in adj) {
19+
//without a solution already...
20+
if(solutions[a])
21+
continue;
22+
//choose nearest node with lowest *total* cost
23+
var d = adj[a] + ndist;
24+
if(d < dist) {
25+
//reference parent
26+
parent = solutions[n];
27+
nearest = a;
28+
dist = d;
29+
}
30+
}
31+
}
32+
33+
34+
if(dist === Infinity) {
35+
break;
36+
}
37+
38+
solutions[nearest] = parent.concat(nearest);
39+
40+
solutions[nearest].dist = dist;
41+
}
42+
43+
return solutions;
44+
}
45+
46+
var graph = {};
47+
48+
\\create graph
49+
50+
var layout = {
51+
'R': ['2'],
52+
'2': ['3','4'],
53+
'3': ['4','6','13'],
54+
'4': ['5','8'],
55+
'5': ['7','11'],
56+
'6': ['13','15'],
57+
'7': ['10'],
58+
'8': ['11','13'],
59+
'9': ['14'],
60+
'10': [],
61+
'11': ['12'],
62+
'12': [],
63+
'13': ['14'],
64+
'14': [],
65+
'15': []
66+
}
67+
68+
//convert uni-directional to bi-directional graph
69+
// needs to look like: where: { a: { b: cost of a->b }
70+
// var graph = {
71+
// a: {e:1, b:1, g:3},
72+
// b: {a:1, c:1},
73+
// c: {b:1, d:1},
74+
// d: {c:1, e:1},
75+
// e: {d:1, a:1},
76+
// f: {g:1, h:1},
77+
// g: {a:3, f:1},
78+
// h: {f:1}
79+
// };
80+
81+
for(var id in layout) {
82+
if(!graph[id])
83+
graph[id] = {};
84+
layout[id].forEach(function(aid) {
85+
graph[id][aid] = 1;
86+
if(!graph[aid])
87+
graph[aid] = {};
88+
graph[aid][id] = 1;
89+
});
90+
}
91+
92+
//choose start node
93+
var start = '10';
94+
//get all solutions
95+
var solutions = solve(graph, start);
96+
97+
console.log("From '"+start+"' to");
98+
//display solutions
99+
for(var s in solutions) {
100+
if(!solutions[s]) continue;
101+
console.log(" -> " + s + ": [" + solutions[s].join(", ") + "] (dist:" + solutions[s].dist + ")");
102+
}

0 commit comments

Comments
 (0)