Public
Edited
Jun 14, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function dijkstra(n, graph, source, destination) {
const distance = new Array(n).fill(Infinity);
const visited = new Array(n);
const parents = [];

distance[source] = 0;
parents[source] = -1;

const priorityQueue = [source];
outerLoop: while (priorityQueue.length > 0) {
const currentNode = getSmallestNodeByDistance(priorityQueue, distance);
visited[currentNode] = true;

for (const node of graph[currentNode]) {
if (visited[node.vertex]) {
continue;
}

const newDistance = distance[currentNode] + node.weight;
if (distance[node.vertex] > newDistance) {
distance[node.vertex] = newDistance;
priorityQueue.push(node.vertex);
parents[node.vertex] = currentNode;
}

if (currentNode === destination) {
break outerLoop;
}
}
}

return {
distance: distance[destination],
path: generatePath(destination, parents)
};
}
Insert cell
{
const source = 0,
destination = 5;
const shortestPath = dijkstra(n, graph, source, destination);

return (
"The shortest distance from 0 to 5 is " +
shortestPath.distance +
" and the shortest path is " +
shortestPath.path.join(" -> ")
);
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more