class PriorityQueue {
constructor() {
this.heap = [];
}
push(val) {
this.heap.push(val);
this.bubbleUp(this.heap.length - 1);
}
pop() {
const poppedVal = this.heap[0];
const bottom = this.heap.length - 1;
if (bottom > 0) {
this.swap(0, bottom);
}
this.heap.pop();
this.sinkDown(0);
return poppedVal;
}
bubbleUp(idx) {
const element = this.heap[idx];
while (idx > 0) {
const parentIdx = Math.floor((idx + 1) / 2) - 1;
const parent = this.heap[parentIdx];
if (element[0] < parent[0]) {
this.swap(idx, parentIdx);
idx = parentIdx;
} else {
break;
}
}
}
sinkDown(idx) {
const length = this.heap.length;
const element = this.heap[idx];
while (true) {
const leftChildIdx = 2 * (idx + 1) - 1;
const rightChildIdx = 2 * (idx + 1);
let leftChild, rightChild;
let swapIdx = null;
if (leftChildIdx < length) {
leftChild = this.heap[leftChildIdx];
if (leftChild[0] < element[0]) {
swapIdx = leftChildIdx;
}
}
if (rightChildIdx < length) {
rightChild = this.heap[rightChildIdx];
if (
(swapIdx === null && rightChild[0] < element[0]) ||
(swapIdx !== null && rightChild[0] < leftChild[0])
) {
swapIdx = rightChildIdx;
}
}
if (swapIdx === null) {
break;
}
this.swap(idx, swapIdx);
idx = swapIdx;
}
}
swap(idx1, idx2) {
[this.heap[idx1], this.heap[idx2]] = [this.heap[idx2], this.heap[idx1]];
}
get length() {
return this.heap.length;
}
get empty() {
return this.heap.length === 0;
}
}
const INF = 0x3f3f3f3f;
class Graph {
constructor(V) {
this.V = V;
this.adj = Array.from({ length: V }, () => []);
}
addEdgeRev(u, v, w) {
this.adj[v].push([u, w]);
}
shortestPath(dest) {
const pq = new PriorityQueue();
const dist = Array.from({ length: this.V }, () => INF);
pq.push([0, dest]);
dist[dest] = 0;
while (!pq.empty) {
const [uDist, u] = pq.pop();
for (const [v, weight] of this.adj[u]) {
if (dist[v] > dist[u] + weight) {
dist[v] = dist[u] + weight;
pq.push([dist[v], v]);
}
}
}
console.log("Destination Vertex Distance from all vertex");
for (let i = 0; i < this.V; i++) {
document.write(`${i} ${dist[i]}`);
}
}
}
const V = 5;
const g = new Graph(V);
g.addEdgeRev(0, 2, 1);
g.addEdgeRev(0, 4, 5)
g.addEdgeRev(1, 4, 1)
g.addEdgeRev(2, 0, 10)
g.addEdgeRev(2, 3, 5)
g.addEdgeRev(3, 1, 1)
g.addEdgeRev(4, 0, 5)
g.addEdgeRev(4, 2, 100)
g.addEdgeRev(4, 3, 5)
g.shortestPath(0)