1. V-1 rounds
A shortest path has at most V-1 edges, so V-1 relaxation passes suffice.
for (let i = 0; i < n - 1; i += 1)Typorithm · hard
Step 1 of 8 · intro card
Graph Algorithms
Relax every edge V-1 times to handle negative weights; one extra round detects negative cycles.
Bellman-Ford finds shortest paths even with negative edge weights, which Dijkstra cannot.
Since a shortest path has at most V-1 edges, V-1 full passes over all edges settle every distance.
If any edge can still be relaxed on a V-th pass, the graph has a negative-weight cycle.
Relax all edges V-1 times.
Handles negative edges.
Extra pass detects negative cycles.
function bellmanFord(edges, n, start) {
const dist = new Array(n).fill(Infinity);
dist[start] = 0;
for (let i = 0; i < n - 1; i += 1) {
for (const [from, to, weight] of edges) {
if (dist[from] + weight < dist[to]) {
dist[to] = dist[from] + weight;
}
}
}
for (const [from, to, weight] of edges) {
if (dist[from] + weight < dist[to]) {
return null;
}
}
return dist;
}Connect each part of the code to the concept before you type.
A shortest path has at most V-1 edges, so V-1 relaxation passes suffice.
for (let i = 0; i < n - 1; i += 1)Each pass tries to improve every edge, unlike Dijkstra's one node at a time.
if (dist[from] + weight < dist[to])Record a shorter distance whenever one is found.
dist[to] = dist[from] + weightA relaxation still possible after V-1 rounds means a negative cycle exists.
return nullRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputDirected graph · start A · edges A→B:4, A→D:2, B→C:3, B→E:1, D→E:5, E→F:2, C→F:4
Follow temporary values, local state and supporting structures at this step.
distances · nodes A–F6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state