Bellman-Ford shortest path

Shortest distance from one source to every node, even with negative edge weights (as long as there is no negative cycle).

Time O(V × E)Space O(V)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Relax every edge, up to V - 1 times: if going through edge (u, v) beats the current best distance to v, update it. Because the shortest path between any two nodes uses at most V - 1 edges, V - 1 full passes are always enough to reach every distance, even with some negative weights.

Code

public static Dictionary<char, int> BellmanFord(
        List<(char u, char v, int w)> edges, char src, int vertexCount) {
    var dist = new Dictionary<char, int>();
    dist[src] = 0;
    for (int i = 0; i < vertexCount - 1; i++) {
        bool changed = false;
        foreach (var (u, v, w) in edges) {
            if (dist.GetValueOrDefault(u, int.MaxValue) != int.MaxValue
                    && dist[u] + w < dist.GetValueOrDefault(v, int.MaxValue)) {
                dist[v] = dist[u] + w;
                changed = true;
            }
        }
        if (!changed) break; // nothing improved, distances are already final
    }
    foreach (var (u, v, w) in edges) // one more pass: if anything still improves, there is a negative cycle
        if (dist[u] + w < dist.GetValueOrDefault(v, int.MaxValue)) throw new Exception("negative cycle");
    return dist;
}
class WEdge { char u, v; int w; }   // edge u -> v with weight w

static Map<Character, Integer> bellmanFord(
        List<WEdge> edges, char src, int vertexCount) {
    final int INF = Integer.MAX_VALUE;
    Map<Character, Integer> dist = new HashMap<>();
    dist.put(src, 0);
    for (int i = 0; i < vertexCount - 1; i++) {
        boolean changed = false;
        for (WEdge e : edges) {
            if (dist.getOrDefault(e.u, INF) != INF
                    && dist.get(e.u) + e.w < dist.getOrDefault(e.v, INF)) {
                dist.put(e.v, dist.get(e.u) + e.w);
                changed = true;
            }
        }
        if (!changed) break; // nothing improved, distances are already final
    }
    for (WEdge e : edges) // one more pass: if anything still improves, there is a negative cycle
        if (dist.containsKey(e.u) && dist.get(e.u) + e.w < dist.getOrDefault(e.v, INF)) throw new IllegalStateException("negative cycle");
    return dist;
}
unordered_map<char, int> bellmanFord(
        const vector<tuple<char, char, int>>& edges, char src, int vertexCount) {
    unordered_map<char, int> dist;
    auto get = [&](char x) { auto it = dist.find(x); return it == dist.end() ? INT_MAX : it->second; };
    dist[src] = 0;
    for (int i = 0; i < vertexCount - 1; i++) {
        bool changed = false;
        for (auto [u, v, w] : edges) {
            if (get(u) != INT_MAX
                    && get(u) + w < get(v)) {
                dist[v] = get(u) + w;
                changed = true;
            }
        }
        if (!changed) break; // nothing improved, distances are already final
    }
    for (auto [u, v, w] : edges) // one more pass: if anything still improves, there is a negative cycle
        if (get(u) != INT_MAX && get(u) + w < get(v)) throw runtime_error("negative cycle");
    return dist;
}
def bellman_ford(edges: list[tuple[str, str, int]], src: str, vertex_count: int) -> dict[str, float]:
    INF = float('inf')
    dist = {}
    dist[src] = 0
    for _ in range(vertex_count - 1):
        changed = False
        for u, v, w in edges:
            if dist.get(u, INF) != INF \
                    and dist[u] + w < dist.get(v, INF):
                dist[v] = dist[u] + w
                changed = True
        if not changed: break  # nothing improved, distances are already final
    for u, v, w in edges:  # one more pass: if anything still improves, there is a negative cycle
        if dist.get(u, INF) + w < dist.get(v, INF): raise ValueError("negative cycle")
    return dist

Tips

In the .NET library

Dijkstra finalises a node's distance the moment it is dequeued, which only works because it always picks the current closest node; a negative edge can undercut an already-finalised distance later, which is exactly what Bellman-Ford guards against by revisiting every edge repeatedly.