function Node(vertex, predecessor, cost) {
this.vertex = vertex;
this.predecessor = predecessor;
this.cost = cost;
}
// O((V + E)logV => ElogV, usually E > V)
function dijkstrasAlgorithm(start, edges) {
const dist = [];
for (let vertex = 0; vertex < edges.length; vertex++) {
dist[vertex] = new Node(vertex, vertex, Infinity);
}
const visited = new Set();
dist[start].cost = 0;
const minHeap = new Heap([], (a, b) => a.cost <= b.cost);
minHeap.insert(new Node(start, start, 0));
while (minHeap.size > 0) {
const {
vertex: here,
predecessor,
cost: currentCost,
} = minHeap.remove();
const adj = edges[here];
for (const [there, incommingCost] of adj) {
if (visited.has(there)) continue;
const prev = dist[there].cost;
const next = currentCost + incommingCost;
if (prev > next) {
dist[there].cost = next;
dist[there].predecessor = here;
minHeap.insert(new Node(there, here, next));
}
}
console.log(minHeap.heap);
visited.add(here);
}
const answer = [];
for (let vertex = 0; vertex < edges.length; vertex++) {
const node = dist[vertex];
answer[vertex] = node.cost === Infinity ? -1 : node.cost;
}
return answer;
}
class Heap {
constructor(arr, predicate = (a, b) => a <= b) {
this.predicate = predicate;
this.size = arr.length;
this.heap = this.buildHeap(arr);
}
buildHeap(arr) {
let currentIndex = Math.floor((arr.length - 1 - 1) / 2);
while (currentIndex >= 0) {
this.siftDown(arr, currentIndex, arr.length - 1);
currentIndex--;
}
return arr;
}
insert(v) {
this.heap.push(v);
this.size++;
this.siftDown(this.heap, 0, this.heap.length - 1);
}
remove(v) {
this.swap(this.heap, 0, this.heap.length - 1);
const elementToRemove = this.heap.pop();
this.size--;
this.siftDown(this.heap, 0, this.heap.length - 1);
return elementToRemove;
}
siftUp(heap, currentIndex) {
let parentIndex = Math.floor((currentIndex - 1) / 2);
while (parentIndex >= 0) {
if (this.predicate(heap[parentIndex], heap[currentIndex])) {
break;
}
this.swap(heap, parentIndex, currentIndex);
currentIndex = parentIndex;
parentIndex = Math.floor((currentIndex - 1) / 2);
}
return heap;
}
siftDown(heap, currentIndex, endIndex) {
let left = currentIndex * 2 + 1;
while (left <= endIndex) {
let min = left;
const right = currentIndex * 2 + 2;
if (heap[right] !== undefined && this.predicate(heap[right], heap[min])) {
min = right;
}
if (this.predicate(heap[currentIndex], heap[min])) break;
this.swap(heap, currentIndex, min);
currentIndex = min;
left = currentIndex * 2 + 1;
}
return heap;
}
swap(arr, a, b) {
[arr[b], arr[a]] = [arr[a], arr[b]];
}
}
// Do not edit the line below.
exports.dijkstrasAlgorithm = dijkstrasAlgorithm;