-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
29 lines (26 loc) · 857 Bytes
/
test.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
const dijkstrasAlgorithm = (graph, startNode) => {
let adjList = createAdjListGraph(graph);
let prev = {};
let pq = new PriorityQueue(adjList.length * adjList.length);
distances[startNode] = 0;
pq.enqueue(startNode, 0);
Object.keys(adjList).forEach(node => {
if (node != startNode) distances[node] = Infinity;
prev[node] = null;
});
while (!pq.isEmpty()) {
let minNode = pq.dequeue();
let currNode = minNode.data;
adjList[currNode].forEach(neighbor => {
let alt = distances[currNode] + neighbor.weight;
if (alt < distances[neighbor.node]) {
distances[neighbor.node] = alt;
prev[neighbor.node] = currNode;
!pq.contain(neighbor.node)
? pq.enqueue(neighbor.node, distances[neighbor.node])
: pq.update(neighbor.node, alt);
}
});
}
return distances;
};