Public
Edited
Jun 23, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function bellmanFord(n, edges) {
const distance = new Array(n).fill(Infinity);
distance[0] = 0;

let isFinished;
for (let i = 0; i < n - 1; i++) {
isFinished = true;
for (const edge of edges) {
const [u, v, w] = edge;
if (distance[u] + w < distance[v]) {
distance[v] = distance[u] + w;
isFinished = false;
}
}
if (isFinished) {
return distance;
}
}

for (let i = 0; i < n - 1; i++) {
for (const edge of edges) {
const [u, v, w] = edge;
if (distance[u] + w < distance[v]) {
distance[v] = distance[u] + w;
return "Negative cycle detected";
}
}
}

return distance;
}
Insert cell
bellmanFord(n, edges)
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