Public
Edited
Jun 15, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
FileAttachment("image@1.png").image()
Insert cell
function floydWarshall(matrix) {
const n = matrix.length;
const dp = matrix.map((row) => [...row]);
const next = Array.from(new Array(n), () => []);

for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] !== Infinity) {
next[i][j] = j;
}
}
}

for (let k = 0; k < n; k++) {
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (dp[i][j] > dp[i][k] + dp[k][j]) {
dp[i][j] = dp[i][k] + dp[k][j];
next[i][j] = next[i][k];
}
}
}
}

return { dp, next };
}
Insert cell
function reconstructPath(matrix, next, source, destination) {
const path = [source];
if (matrix[source][destination] === Infinity) {
return path;
}

let node = next[source][destination];
while (node !== destination) {
path.push(node);
node = next[node][destination];
}
path.push(destination);

return {distance: matrix[source][destination], path};
}
Insert cell
result = floydWarshall(graph)
Insert cell
{
const source = 2,
destination = 0;
const { distance, path } = reconstructPath(
result.dp,
result.next,
source,
destination
);
return `The minimum distance is ${distance} and the path is ${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