-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdijkstras algorithm.js
89 lines (75 loc) · 1.88 KB
/
dijkstras algorithm.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
const graph = {
'start': { 'A': 5, 'B': 2 },
'A': { 'C': 4, 'D': 2 },
'B': { 'A': 8, 'D': 7 },
'C': { 'finish': 3, 'D': 6 },
'D': { 'finish': 1 },
'finish': {}
};
const costs = {
'A': 5,
'B': 2,
'C': Infinity,
'D': Infinity,
'finish': Infinity
};
const parents = {
'A': 'start',
'B': 'start',
'C': null,
'D': null,
'finish': null
};
class Djkstra {
constructor(graph) {
this.processed = [];
this.graph = graph || null;
this.costs = {};
this.parents = {};
}
createCosts(graph) {
const keys = Object.keys(graph);
keys.forEach(el => {
if (el == 'start') return;
this.costs[el] = Infinity;
});
Object.keys(graph[keys[0]]).forEach(el => {
this.costs[el] = graph[keys[0]][el];
});
}
createParents(graph) {
const keys = Object.keys(graph);
keys.forEach(el => {
if (el == 'start') return;
this.parents[el] = null;
});
Object.keys(graph[keys[0]]).forEach(el => {
this.parents[el] = keys[0];
});
}
createGraph(element, filler, initial) {
const keys = Object.keys(this.graph);
keys.forEach(el => {
if (el == 'start') return;
element[el] = filler;
});
Object.keys(graph[keys[0]]).forEach(el => {
element[el] = initial;
});
}
findLowestCostNode(costs) {
let lowestCost = Infinity,
lowestCostNode = null;
for (let i in costs) {
if (this.processed.includes(i)) continue;
if (costs[i] < lowestCost) {
lowestCost = costs[i];
lowestCostNode = i;
}
};
return lowestCostNode;
}
}
const a = new Djkstra();
a.createCosts(graph);
a.createParents(graph);