arctic λime

bmssp series 3 - bellman ford

In the first article of this series, we explored Dijkstra and its pitfalls. One major limitation: Dijkstra fails with negative edges.

But here's the thing, Dijkstra already uses the operation that CAN handle negative edges: edge relaxation (from the previous article). The problem isn't the relaxation operation itself, but rather Dijkstra's greedy strategy of visiting nodes in a specific order and never reconsidering them.

Bellman Ford's algorithm shows us that by applying the same edge relaxation operation differently (systematically and repeatedly rather than greedily) we can handle negative edges correctly.

Here's the minimal implementation based on our previous Dijkstra implementation:

def bellman_ford_minimal(graph, start, end):
    dist = {node: float('inf') for node in graph}
    dist[start] = 0.0

    # Relax edges up to |V|-1 times
    for _ in range(len(graph) - 1):
        updated = False
        for u in graph:
            for v, w in graph[u]:
                if dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w
                    updated = True
        if not updated:
            break

    return dist[end]

# Example usage
graph = {
    'A': [('B', 4), ('C', 2)],
    'B': [('A', 4), ('C', -2), ('D', 5)], # B -> C is now -2
    'C': [('A', 2), ('B', 1), ('D', 8), ('E', 10)],
    'D': [('B', 5), ('C', 8), ('E', -4), ('F', 6)], # D -> E is now -4
    'E': [('C', 10), ('D', 2), ('F', 3)],
    'F': [('D', 6), ('E', 3)]
}

print(bellman_ford_minimal(graph, 'A', 'F'))  # Output: 0.0!

First thing you would probably notice if you open them side-by-side is the lack of heapq import. BF doesn't need to use a heap, it systematically checks and updates the shortest distances without prioritizing nodes by their current shortest distance (as Dijkstra's algorithm does.) This makes a priority queue unnecessary. For the implementation, "systematically" means relaxing all edges in the graph up to |V|−1 times1 (len(graph) - 1).

There is also an early stopping optimization where the algorithm terminates before completing all |V|−1 iterations if no distance updates (relaxations) occur during a complete iteration over all edges (marked by updated). If there are no updates (= no distance improvements), the loop breaks early.

These two concepts together help us understand the concept of frontier (or upper bound) in the Bellman-Ford algorithm, mentioned in Dijkstra and key in the bmssp implementation. In this case, our upper bound is the |V|−1.

There's also another major change, B→C and D→E have negative weights now, making the shortest distance A→F=0 now. If we enter these new edge values in the Dijkstra algorithm, we can see the output is 7. The algorithm doesn't crash or anything, but this result does not mean Dijkstra is working correctly: Dijkstra's algorithm is not designed to handle graphs with negative edge weights because it relies on the assumption that once a node is visited (finalized), its shortest distance is known and cannot be improved. Negative edges can violate this assumption because a shorter path may appear later through a negative edge, but Dijkstra will not revisit nodes already marked visited. This is the main conceptual difference between the two.

In terms of efficiency, BF's systematic scanning is inefficient when all edge weights are positive (compared to Dijkstra's selective approach). It is slower. This complexity is higher especially for large dense graphs.

There are however a few improvements we can make to make it faster (this, or other path-finding algorithms). We can...

  1. Limit relaxation steps to k (in BF, k=|V|−1, the least we can do).
  2. Limit distance values to avoid infinite propagation.

For example, bounding relaxation within a distance B or limiting iteration count can prune unnecessary computations. These bounds help control runtime and can focus the algorithm on relevant subgraphs or distance ranges.

Relating this last paragraph with the series' topic, BMSSP's success is mostly based on subdividing the graph and applying bounded relaxations on subsets of vertices to optimize shortest path computations. It exploits k-step relaxation and distance bounds to narrow the search space and speed things up.

We're getting closer! In the next article I'll be introducing these bounds with a bounded implementation of Dijkstra.

  1. The reason why |V|−1 iterations are enough in the Bellman-Ford algorithm is based on the fact that any shortest path in a graph without negative cycles cannot have more than |V|−1 edges.↩