Reading history

Bellman-Ford Algorithm in C: Shortest Paths with Negative Weights

7 min read 1 views

Learn the Bellman-Ford algorithm in C: edge relaxation, V-1 passes, early stopping, path rebuilding, negative cycle detection and why Dijkstra fails.

Dijkstra’s algorithm finds shortest paths quickly, but it can give wrong answers when some edges have negative weights, such as a discount, a refund or an energy gain. The Bellman-Ford algorithm handles negative weights correctly. It is slower, but it can also detect a negative cycle: a loop whose total cost is below zero, where “shortest path” stops making sense because going round again always costs less. This lesson implements Bellman-Ford in C, prints the distances after each pass, and uses it to spot negative cycles.

In this lesson you will learn

  • Edge relaxation and why V − 1 passes are enough
  • Implementing Bellman-Ford with an edge list in C
  • Stopping early when nothing changes
  • Rebuilding the shortest path with a parent array
  • Detecting negative cycles, and why Dijkstra fails with negative edges

You should know graph basics and Dijkstra’s algorithm.

Bellman-Ford Step by Step

#include <stdio.h>
#include <limits.h>

#define V 5
#define INF INT_MAX

struct edge { int from, to, w; };

/* Bellman-Ford: shortest paths from src, negative weights allowed.
   Returns 0 if a negative cycle is reachable, 1 otherwise. */
static int bellman_ford(const struct edge *e, int m, int src, int dist[], int parent[]) {
    for (int i = 0; i < V; i++) { dist[i] = INF; parent[i] = -1; }
    dist[src] = 0;

    for (int pass = 1; pass <= V - 1; pass++) {          /* relax every edge V-1 times */
        int changed = 0;
        for (int j = 0; j < m; j++) {
            int u = e[j].from, v = e[j].to, w = e[j].w;
            if (dist[u] != INF && dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                parent[v] = u;
                changed = 1;
            }
        }
        printf("after pass %d: ", pass);
        for (int i = 0; i < V; i++) {
            if (dist[i] == INF) printf("  inf");
            else printf("%5d", dist[i]);
        }
        printf("\n");
        if (!changed) break;                              /* nothing improved: finished early */
    }
    for (int j = 0; j < m; j++)                           /* one more pass: any improvement = cycle */
        if (dist[e[j].from] != INF && dist[e[j].from] + e[j].w < dist[e[j].to]) return 0;
    return 1;
}

static void print_path(const int parent[], int v) {
    if (parent[v] != -1) { print_path(parent, parent[v]); printf(" -> "); }
    printf("%d", v);
}

int main(void) {
    struct edge e[] = {
        {0, 1, 6}, {0, 2, 7}, {1, 2, 8}, {1, 3, 5}, {1, 4, -4},
        {2, 3, -3}, {2, 4, 9}, {3, 1, -2}, {4, 3, 7},
    };
    int m = sizeof e / sizeof e[0];
    int dist[V], parent[V];

    if (bellman_ford(e, m, 0, dist, parent)) {
        for (int v = 1; v < V; v++) {
            printf("0 to %d: cost %3d, path ", v, dist[v]);
            print_path(parent, v);
            printf("\n");
        }
    }
    return 0;
}

Output

after pass 1:     0    2    7    4    2
after pass 2:     0    2    7    4   -2
after pass 3:     0    2    7    4   -2
0 to 1: cost   2, path 0 -> 2 -> 3 -> 1
0 to 2: cost   7, path 0 -> 2
0 to 3: cost   4, path 0 -> 2 -> 3
0 to 4: cost  -2, path 0 -> 2 -> 3 -> 1 -> 4
  • The graph is stored as a simple edge list: each edge has a start, an end and a weight. Bellman-Ford does not need an adjacency matrix.
  • All distances start at “infinity” except the source, which is 0.
  • Relaxing an edge u → v means checking whether going through u gives v a shorter distance: if dist[u] + w < dist[v], update dist[v] and remember u as v’s parent.
  • One pass relaxes every edge once. A shortest path uses at most V − 1 edges, and each pass fixes at least one more edge of every shortest path, so V − 1 passes are always enough.
  • In this graph the answers settled after two passes; the third pass changed nothing, so the loop stopped early. In the worst case all V − 1 passes are needed.
  • The check dist[u] != INF before adding avoids overflowing INT_MAX.
  • Following parent links back from a vertex rebuilds its path. The cheapest route to vertex 4 uses the negative edges 2 → 3 and 1 → 4.

Negative Cycles

#include <stdio.h>
#include <limits.h>

#define INF INT_MAX

struct edge { int from, to, w; };

static int has_negative_cycle(const struct edge *e, int m, int n, int src) {
    int dist[16];
    for (int i = 0; i < n; i++) dist[i] = INF;
    dist[src] = 0;
    for (int pass = 1; pass < n; pass++)
        for (int j = 0; j < m; j++)
            if (dist[e[j].from] != INF && dist[e[j].from] + e[j].w < dist[e[j].to])
                dist[e[j].to] = dist[e[j].from] + e[j].w;
    for (int j = 0; j < m; j++)
        if (dist[e[j].from] != INF && dist[e[j].from] + e[j].w < dist[e[j].to])
            return 1;
    return 0;
}

int main(void) {
    /* Currency exchange as a graph: weight = cost of a trade, in points.
       A cycle whose total cost is negative is an "arbitrage": a loop that makes money. */
    struct edge ok[] = { {0, 1, 4}, {1, 2, -2}, {2, 3, 3}, {3, 1, 1} };     /* cycle 1-2-3-1 costs +2 */
    struct edge bad[] = { {0, 1, 4}, {1, 2, -2}, {2, 3, 3}, {3, 1, -3} };   /* cycle 1-2-3-1 costs -2 */

    printf("graph A: %s\n", has_negative_cycle(ok, 4, 4, 0) ? "negative cycle found" : "no negative cycle");
    printf("graph B: %s\n", has_negative_cycle(bad, 4, 4, 0) ? "negative cycle found" : "no negative cycle");

    /* Why Dijkstra fails with negative edges: it settles node 1 too early */
    struct edge tricky[] = { {0, 1, 2}, {0, 2, 5}, {2, 1, -4} };
    int dist[3] = {0, INF, INF};
    for (int pass = 1; pass < 3; pass++)
        for (int j = 0; j < 3; j++)
            if (dist[tricky[j].from] != INF && dist[tricky[j].from] + tricky[j].w < dist[tricky[j].to])
                dist[tricky[j].to] = dist[tricky[j].from] + tricky[j].w;
    printf("tricky graph: Bellman-Ford gives 0 to 1 = %d (Dijkstra would stop at 2)\n", dist[1]);
    return 0;
}

Output

graph A: no negative cycle
graph B: negative cycle found
tricky graph: Bellman-Ford gives 0 to 1 = 1 (Dijkstra would stop at 2)
  • After V − 1 passes, every true shortest distance is final. If one more pass can still improve some distance, the graph must contain a negative cycle reachable from the source.
  • Graph A’s loop 1 → 2 → 3 → 1 costs −2 + 3 + 1 = +2, which is fine. In graph B the same loop costs −2, so the extra pass finds an improvement and reports a cycle.
  • In currency trading, edge weights can be the negative logarithms of exchange rates. A negative cycle then means a series of trades that ends with more money than it started with, called an arbitrage.
  • In the “tricky” graph, Dijkstra would finalise vertex 1 at distance 2 because it is the closest unvisited vertex, and never revisit it. The true best route goes 0 → 2 → 1 for 5 − 4 = 1. Bellman-Ford finds it because it keeps relaxing every edge.

Bellman-Ford vs Dijkstra

DijkstraBellman-Ford
Negative edge weightsNot allowedAllowed
Detects negative cyclesNoYes
TimeO((V + E) log V) with a heapO(V × E)
Typical useRoad maps, network routingGraphs with negative costs, arbitrage, distance-vector routing (RIP)

Common Mistakes

  1. Adding to an infinite distance, which overflows. Check dist[u] != INF first.
  2. Running only one pass and assuming the result is final.
  3. Forgetting the extra pass that detects negative cycles, and printing meaningless distances.
  4. Treating an undirected negative edge as two directed edges: that pair already forms a negative cycle of length two.

Practice Exercises

Exercise 1. How many times is an edge relaxed in the worst case for a graph with 5 vertices and 9 edges?

Show answer

(V − 1) × E = 4 × 9 = 36 relaxations, plus 9 more for the negative-cycle check.

Exercise 2. Change bellman_ford so it prints the vertices that can be reached from the source, and “unreachable” for the rest.

Show answer
for (int v = 0; v < V; v++) {
    if (dist[v] == INF) printf("%d: unreachable\n", v);
    else printf("%d: %d\n", v, dist[v]);
}

Frequently Asked Questions

Why is Bellman-Ford slower than Dijkstra?

Dijkstra settles each vertex once, choosing the closest one with a priority queue. Bellman-Ford makes no such choice; it relaxes every edge in every pass, giving O(V × E) time, which is much more for large graphs.

Can Bellman-Ford find which vertices are on the negative cycle?

Yes. Record a vertex whose distance improves in the extra pass, follow parent links V times to be sure you are inside the cycle, then keep following them until you return to the same vertex.

Summary

  • Bellman-Ford relaxes every edge V − 1 times and works with negative weights.
  • An improvement in an extra pass means a negative cycle.
  • It runs in O(V × E) time and can stop early when nothing changes.
  • Use Dijkstra when all weights are non-negative; it is much faster.

Next: Floyd-Warshall Algorithm in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *