Practice GFG · Bellman-Ford Algorithm · LeetCode 787 · Cheapest Flights (related)
GraphsDPWeightedNegative OK

Bellman-Ford · Shortest Paths

Dijkstra's slower but braver cousin. It relaxes every edge V-1 times, so it handles negative weights and one extra pass tells you if a negative cycle exists.

Why V-1 passes

A shortest path visits at most V-1 edges. Each full pass over all edges guarantees one more edge of every shortest path is locked in, so V-1 passes settle everything.

Negative cycle check

  • Relax all edges, repeated V-1 times
  • Relaxation: if dist[u]+w < dist[v] update
  • Run one more pass, still improving?
  • Yes → a negative-weight cycle exists

Relax pass by pass

∞ / untouched Relaxed this pass Has finite dist
Pass 0 of 4
slowfast
Step 0
Pass
0
Relaxations
0
Edge
–
Neg cycle?
?

C++

bool bellmanFord(int n, int src,
                 vector<array<int,3>>& edges, vector<int>& dist) {
    dist.assign(n, INT_MAX);
    dist[src] = 0;

    // V-1 passes: each relaxes every edge once
    for (int i = 1; i < n; i++)
        for (auto& [u, v, w] : edges)
            if (dist[u] != INT_MAX && dist[u] + w < dist[v])
                dist[v] = dist[u] + w;      // relax

    // one more pass: any improvement = negative cycle
    for (auto& [u, v, w] : edges)
        if (dist[u] != INT_MAX && dist[u] + w < dist[v])
            return false;              // negative cycle detected

    return true;                          // dist[] holds shortest paths
}
Time
O(V × E)

V-1 passes, each scanning all E edges. Slower than Dijkstra.

Space
O(V)

Just the distance array; edges can stay in an edge list.

Handles
neg edges

And uniquely, detects negative-weight cycles.

  • When to reach for it: negative edge weights, or you specifically need to detect a negative cycle. Otherwise Dijkstra is faster.
  • Guard with dist[u] != INT_MAX before relaxing, or INT_MAX + w overflows.
  • Early exit: if a full pass makes zero relaxations, you're done, skip the rest.
  • SPFA is a queue-based optimization of Bellman-Ford, faster in practice but same worst case.
  • Cheapest Flights within K stops is Bellman-Ford capped at K+1 passes.