-
Notifications
You must be signed in to change notification settings - Fork 1
/
dijkstra.js
53 lines (46 loc) · 1.31 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
const graph = {
start: {A: 5, B: 2},
A: {C: 4, D: 2},
B: {A: 8, D: 7},
C: {D: 6, end: 3},
D: {end: 1},
end: {}
};
console.info(dijkstraAlgorithm(graph));
function dijkstraAlgorithm(graph) {
const costs = Object.assign({end: Infinity}, graph.start);
const parents = {end: null};
const processed = [];
let node = findLowestCostNode(costs, processed);
while (node) {
let cost = costs[node];
let children = graph[node];
for (let n in children) {
let newCost = cost + children[n];
if (!costs[n] || costs[n] > newCost) {
costs[n] = newCost;
parents[n] = node;
}
}
processed.push(node);
node = findLowestCostNode(costs, processed);
}
let optimalPath = ['end'];
let parent = parents.end;
while (parent) {
optimalPath.push(parent);
parent = parents[parent];
}
optimalPath.reverse();
return {distance: costs.end, path: optimalPath};
};
function findLowestCostNode(costs, processed) {
return Object.keys(costs).reduce((lowest, node) => {
if (lowest === null || costs[node] < costs[lowest]) {
if (!processed.includes(node)) {
lowest = node;
}
}
return lowest;
}, null);
};