Dijkstra's Algorithm to find the shortest path in javascript
π‘ Notes
can be used only positive weight graph.
kind of Greedy algorithm
best-first search : shortest path first search
β¨ Algorithm
From the start node, do the edge relaxation of the next nodes and update the shorted path to that node.
Select and move to the shorted node among the newly relaxated nodes.
Repeat this.
Common
// adjcent list : graph// All nodes are set to Infinityconst costs =Array(n +1).fill(Infinity);// except starting point
costs[k]=0;
using nested-for statement : [object Object]
π₯ using min-heap : [object Object]
// [ node, cost ]const minHeap =newMinPriorityQueue({compare:(a, b)=> a[1]- b[1]});
minHeap.enqueue([k,0]);while(minHeap.size()){const[cur, cost]= minHeap.dequeue();// validation (for easy usage of heap)// - matched: latest smallest one// - not matched: old one which is reduced to smaller one due to the relaxationif(costs[cur]!== cost)continue;if(graph[cur]===undefined)continue;for(const[next, nextCost]of graph[cur]){// relaxationif(costs[next]> costs[cur]+ nextCost){
costs[next]= costs[cur]+ nextCost;
minHeap.enqueue([next, costs[next]]);}}}