type Edge = { from: number; to: number; weight: number }; function bellmanFord(edges: Edge[], vertices: number, source: number): number[] { const dist = Array(vertices).fill(Infinity); dist[source] = 0; for (let i = 1; i < vertices; i++) { for (const edge of edges) { if (dist[edge.from] + edge.weight < dist[edge.to]) { dist[edge.to] = dist[edge.from] + edge.weight; } } } return dist; } const edges = [ { from: 0, to: 1, weight: 4 }, { from: 0, to: 2, weight: 5 }, { from: 1, to: 2, weight: -3 }, { from: 2, to: 3, weight: 4 }, { from: 3, to: 1, weight: -6 } ]; const result = bellmanFord(edges, 4, 0); console.log(result);
The algorithm updates distances by relaxing edges repeatedly. After 3 iterations (V-1), the distances array is [0, -11, -9, -5].
Bellman-Ford runs V-1 iterations to relax edges. If any edge can still be relaxed after that, it means a cycle reduces path cost indefinitely, indicating a negative weight cycle.
function bellmanFordBug(edges: {from:number,to:number,weight:number}[], vertices:number, source:number): number[] {
const dist = Array(vertices).fill(Infinity);
dist[source] = 0;
for (let i = 0; i < vertices; i++) {
for (const edge of edges) {
if (dist[edge.from] + edge.weight < dist[edge.to]) {
dist[edge.to] = dist[edge.from] + edge.weight;
}
}
}
return dist;
}The Bellman-Ford algorithm should run the relaxation loop exactly V-1 times. Running it V times can cause incorrect results or unnecessary computations.
Bellman-Ford requires iterating over all edges repeatedly. An edge list directly stores edges, making iteration simple and efficient.
type Edge = { from: number; to: number; weight: number }; function bellmanFordDetectCycle(edges: Edge[], vertices: number, source: number): string { const dist = Array(vertices).fill(Infinity); dist[source] = 0; for (let i = 1; i < vertices; i++) { for (const edge of edges) { if (dist[edge.from] + edge.weight < dist[edge.to]) { dist[edge.to] = dist[edge.from] + edge.weight; } } } for (const edge of edges) { if (dist[edge.from] + edge.weight < dist[edge.to]) { return "Negative cycle detected"; } } return JSON.stringify(dist); } const edges = [ { from: 0, to: 1, weight: 1 }, { from: 1, to: 2, weight: -1 }, { from: 2, to: 0, weight: -1 } ]; const output = bellmanFordDetectCycle(edges, 3, 0); console.log(output);
The graph contains a cycle with total negative weight. Bellman-Ford detects this by finding an edge that can still be relaxed after V-1 iterations, returning the "Negative cycle detected" message.