-
Notifications
You must be signed in to change notification settings - Fork 26
/
dijkstra.js
53 lines (48 loc) · 1.06 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
let graph = {};
graph['start'] = {};
graph['start']['a'] = 6;
graph['start']['b'] = 2;
graph['a'] = {};
graph['a']['fin'] = 1;
graph['b'] = {};
graph['b']['a'] = 3;
graph['b']['fin'] = 5;
graph['fin'] = {};
let costs = {};
costs['a'] = 6;
costs['b'] = 2;
costs['fin'] = Infinity;
let parents = {};
parents['a'] = 'start';
parents['b'] = 'start';
parents['fin'] = null;
let processed = [];
function dijkstra() {
let node = findLowerCostNode(costs);
while(node !== null){
let cost = costs[node];
let neighbors = graph[node];
for(let n in neighbors){
let newCost = cost + neighbors[n];
if(costs[n] > newCost){
costs[n] = newCost;
parents[n] = node;
}
}
processed.push(node);
node = findLowerCostNode(costs);
}
}
function findLowerCostNode (costs) {
let lowerCostNode = null;
let lowerCost = Infinity;
for(let node in costs){
let cost = costs[node];
if(cost < lowerCost && processed.indexOf(node) === -1){
lowerCost = cost;
lowerCostNode = node;
}
}
return lowerCostNode;
}
dijkstra();