Master the Bellman-Ford algorithm step-by-step: edge relaxation loops, handling negative edge weights, detecting negative cycles, and JavaScript implementation.
The Bellman-Ford algorithm computes single-source shortest paths in a directed or undirected graph, even when edge weights are negative.
Unlike Dijkstra's algorithm, Bellman-Ford can handle negative edge weights and will reliably detect if the graph contains a negative weight cycle (a cycle whose total weight sum is negative).
Set distance to source vertex to 0 and all other V - 1 vertices to Infinity.
Iterate (V - 1) times. In each pass, for every edge (u, v) with weight w, if dist[u] + w < dist[v], update dist[v] = dist[u] + w.
Run an additional V-th relaxation pass over all edges. If dist[u] + w < dist[v] is still true for any edge, a Negative Weight Cycle exists!
1function bellmanFord(vertices, edges, source) {2 const dist = new Array(vertices).fill(Infinity);3 dist[source] = 0;4 5 // Step 1: Relax all edges (V - 1) times6 for (let i = 1; i <= vertices - 1; i++) {7 for (const [u, v, w] of edges) {8 if (dist[u] !== Infinity && dist[u] + w < dist[v]) {9 dist[v] = dist[u] + w;10 }11 }12 }13 14 // Step 2: Check for negative-weight cycles15 for (const [u, v, w] of edges) {16 if (dist[u] !== Infinity && dist[u] + w < dist[v]) {17 throw new Error("Graph contains a negative weight cycle!");18 }19 }20 21 return dist;22}23 24// Example usage:25// 5 vertices (0 to 4), edges [u, v, weight]26// const edges = [27// [0, 1, -1], [0, 2, 4],28// [1, 2, 3], [1, 3, 2], [1, 4, 2],29// [3, 2, 5], [3, 1, 1],30// [4, 3, -3]31// ];32// bellmanFord(5, edges, 0); // Returns [0, -1, 2, -1, 1]The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Test your understanding of Bellman-Ford Algorithm complexity and step mechanics.
Q1.Why does Bellman-Ford relax edges exactly (V - 1) times?
Q2.How does Bellman-Ford detect negative weight cycles reachable from the source?
Apply Bellman-Ford Algorithm to real coding interview questions.
Find the cheapest price from src to dst with at most k stops using a modified Bellman-Ford approach.