JSFiddle - React, Tailwind, and code Playground
JavaScript
console.clear();
let c = (...s) => console.log(...s);
// DIJKSTRA'S ALGORITHM
// Node and it's neighbours
// cost is from node --> neighbour
let graph = {};
graph = {
start: {
a: 6,
b: 2
},
a: {
fin: 1
},
b: {
a: 3,
fin: 5
},
fin: {}
}
// cost is from start node --> any other node
let cost = {
a: 6,
b: 2,
fin: Infinity
};
// parents
let parents = {
a: "start",
b: "start",
fin: null
};
let processed = []; // processed nodes
function findLowestCostNodeFromStart() {
let lowestCost = Infinity;
let nodeWithLowestCost = null;
for (i in cost) {
if (processed.includes(i)) continue;
if (cost[i] < lowestCost) {
lowestCost = cost[i];
nodeWithLowestCost = i;
}
}
return nodeWithLowestCost;
}
// processing of node and it's neighbours
let node = findLowestCostNodeFromStart();
while (node != null) {
let costOfNode = cost[node];
let neighbours = graph[node];
for (n in neighbours) {
let costOfNodesNeighbour = costOfNode + neighbours[n];
if (costOfNodesNeighbour < cost[n]) {
cost[n] = costOfNodesNeighbour;
parents[n] = node;
}
}
processed.push(node);
node = findLowestCostNodeFromStart();
}
c(processed);
c(cost);
c(parents);