-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstras-algorithm.js
More file actions
108 lines (100 loc) · 1.75 KB
/
dijkstras-algorithm.js
File metadata and controls
108 lines (100 loc) · 1.75 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class PriorityQueue {
constructor(){
this.items = [];
}
isEmpty(){
return this.items.length === 0;
}
enqueue(node){
//Push node into approparite place in queue
for (var i = 0; i < this.items.length; i++){
if (node.dist < this.items[i].dist){
this.items.splice(i, 0, node);
break;
}
}
if (i === this.items.length){
this.items.push(node);
}
}
dequeue(){
return this.items.shift();
}
toString(){
return this.items.toString();
}
}
const graph = [
[
{to:1, weight:2},
{to:3, weight:1}
],
[
{to:3, weight:3},
{to:4, weight:10}
],
[
{to:0, weight:4},
{to:5, weight:5}
],
[
{to:2, weight:2},
{to:4, weight:2},
{to:5, weight:8},
{to:6, weight:4}
],
[
{to:6, weight:6}
],
[],
[
{to:5, weight:1}
],
];
function dijkstras(graph, start){
const info = new Array(graph.length); //{dist:fromStart, prev:index}
for (var i = 0; i < info.length; i++){
info[i] = {
dist:Infinity,
prev:-1
};
}
info[start].dist = 0;
const pq = new PriorityQueue();
pq.enqueue({
index:start,
dist:0
});
while (!pq.isEmpty()){
//console.log(pq);
const node = pq.dequeue();
const paths = graph[node.index];
for (var i = 0; i < paths.length; i++){
const path = paths[i];
const dist = info[node.index].dist + path.weight;
if (dist < info[path.to].dist){
info[path.to].dist = dist;
info[path.to].prev = node.index;
pq.enqueue({
index:path.to,
dist:dist
});
}
}
}
return info;
}
function getPath(info, start, end){
var path = [end];
var node = info[end];
while (node.prev !== -1){
path.push(node.prev);
node = info[node.prev];
}
path.reverse();
return path;
}
const info = dijkstras(graph, 0);
console.log(info);
const path = getPath(info, 0, 5);
console.log(path);