-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgo.js
More file actions
67 lines (59 loc) · 2.11 KB
/
algo.js
File metadata and controls
67 lines (59 loc) · 2.11 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
const graph = require('./weightedGraph');
const nodesPriQueue = require('./prioQueue');
const dijkstraAlgo = (start, finish) => {
const distances = {};
const prevVertex = {};
const pathToTarget = [];
// Set Infinity distances except for start node & prevVertex to null
for (let vertex in graph.adjacencyList) {
distances[vertex] = vertex === start ? 0 : Infinity;
prevVertex[vertex] = null;
}
// Include all nodes to the priority q to know which to pick next
for (let vertex in graph.adjacencyList)
vertex === start
? nodesPriQueue.enqueue(vertex, 0)
: nodesPriQueue.enqueue(vertex, Infinity);
// While queue is not empty
let smallest;
while (nodesPriQueue.values.length) {
smallest = nodesPriQueue.dequeue().value;
// If we reached the target, break and construct path to target
if (smallest === finish) {
// console.log(distances);
// console.log(prevVertex);
// Build path to return - Loop through prevVertex and create the path
while (prevVertex[smallest]) {
pathToTarget.push(smallest);
smallest = prevVertex[smallest];
}
break;
}
if (smallest || distances[smallest] !== Infinity) {
// Loop over all neighbours of this current vertes
graph.adjacencyList[smallest].forEach((neigh) => {
// console.log(neigh.node, '✅✅');
// Potential new distance to this neighbour
const newDistance = distances[smallest] + neigh.weight;
// Check if new distance is less than curr distance to the neigh
if (newDistance < distances[neigh.node]) {
// Update distance
distances[neigh.node] = newDistance;
// Update prev vertext of the neigh to be the smallest - curr node
prevVertex[neigh.node] = smallest;
// Updates nodes priority in the queue
nodesPriQueue.enqueue(neigh.node, newDistance);
}
});
}
}
const path = pathToTarget.concat(smallest).reverse().join(' -> ');
console.log(path);
return path;
};
dijkstraAlgo('A', 'D');
// A
// 4 / \ 1
// B --3-- C
// 6 \ / 8
// D