To get the shortest
path, we also check if it is possible to reach the destination
node from the source
node, as there is a possibility that it may not be reachable. The destination node is then added to the list of routes which gives us the shortest path.
xxxxxxxxxx
90
dijkstra(graph, "a", "f");
const graph = {
a: { b: 5, c: 2 },
b: { a: 5, c: 7, d: 8 },
c: { a: 2, b: 7, d: 4, e: 8 },
d: { b: 8, c: 4, e: 6, f: 4 },
e: { c: 8, d: 6, f: 3 },
f: { e: 3, d: 4 },
};
​
const printTable = (table) => {
return Object.keys(table)
.map((vertex) => {
var { vertex: from, cost } = table[vertex];
return `${vertex}: ${cost} via ${from}`;
})
.join("\n");
};
​
const tracePath = (table, start, end) => {
var path = [];
var next = end;
while (true) {
path.unshift(next);
if (next === start) {
break;
}
next = table[next].vertex;
}
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment