-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.js
89 lines (74 loc) · 2.19 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
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
class PriorityQueue {
constructor() {
this.queue = [];
}
enqueue(element, priority) {
this.queue.push({ element, priority });
this.sort();
}
dequeue() {
if (this.isEmpty()) return null;
return this.queue.shift().element;
}
sort() {
this.queue.sort((a, b) => a.priority - b.priority);
}
isEmpty() {
return this.queue.length === 0;
}
}
class Graph {
constructor() {
this.vertices = {};
}
addVertex(vertex) {
if (!this.vertices[vertex]) {
this.vertices[vertex] = {};
}
}
addEdge(source, destination, weight) {
this.vertices[source][destination] = weight;
//this.vertices[destination][source] = weight;
}
dijkstra(startVertex) {
let distances = {};
let visited = {};
let priorityQueue = new PriorityQueue();
for (let vertex in this.vertices) {
distances[vertex] = Infinity;
visited[vertex] = false;
}
distances[startVertex] = 0;
priorityQueue.enqueue(startVertex, 0);
while (!priorityQueue.isEmpty()) {
let currentVertex = priorityQueue.dequeue();
visited[currentVertex] = true;
for (let neighbor in this.vertices[currentVertex]) {
let distance = distances[currentVertex] + this.vertices[currentVertex][neighbor];
if (distance < distances[neighbor]) {
distances[neighbor] = distance;
if (!visited[neighbor]) {
priorityQueue.enqueue(neighbor, distance);
}
}
}
}
return distances;
}
}
const graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addVertex("E");
graph.addEdge("A", "B", 4);
graph.addEdge("A", "C", 2);
graph.addEdge("B", "C", 5);
graph.addEdge("B", "D", 10);
graph.addEdge("C", "D", 3);
graph.addEdge("C", "E", 7);
graph.addEdge("D", "E", 8);
const startVertex = "A";
const distances = graph.dijkstra(startVertex);
console.log("Shortest distances from vertex", startVertex, ":", distances);