Public
Edited
Jun 14, 2023
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
image = FileAttachment("image.png").image()
Insert cell
Insert cell
function shortestPathUsingTopSort(n, graph, source, destination) {
const topSortArray = topSort(graph);
const distance = new Array(n).fill(Infinity);
const parents = [];

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

for (let i = 0; i < topSortArray.length; i++) {
const nodeIndex = topSortArray[i];

if (!graph[nodeIndex]) {
continue;
}

for (const node of graph[nodeIndex]) {
const currentDistance = distance[nodeIndex] + node.weight;
if (currentDistance < distance[node.vertex]) {
parents[node.vertex] = nodeIndex;
distance[node.vertex] = currentDistance;
}
}
}

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

return (
"The shortest distance from 0 to 7 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