Back to Home

Bellman-Ford Algorithm

An algorithm that computes shortest paths from a single source vertex to all other vertices in a weighted digraph, even with negative edge weights.

Visualization

Step 1 / 8
Speed:

Details

Analogy

Imagine a currency exchange market with various conversion rates. Some 'rates' (edges) might be beneficial (negative weight) due to arbitrage opportunities. You want to find the 'cheapest' way to convert your home currency to all others. Bellman-Ford is like iterating through all possible trades (edges) many times. Each time, you see if a new trade can give you a better deal for any currency. After enough iterations, you'll have the best rates. If prices keep getting better indefinitely, it means there's a profitable loop (a negative cycle).

Purpose

To find the shortest paths from a source to all other nodes in a graph that may contain negative edge weights. It can also detect negative weight cycles.

Use Cases

Used in routing protocols where edge weights can represent various metrics, and for detecting arbitrage opportunities in finance. It's slower than Dijkstra's but more versatile due to its ability to handle negative weights.

Algorithm Steps

Line 1
1
initialize distances to infinity, dist[start] = 0
2
for i = 1 to V-1:
3
for each edge (u, v) with weight w:
4
if dist[u] + w < dist[v]:
5
dist[v] = dist[u] + w
6
for each edge (u, v) with weight w:
7
if dist[u] + w < dist[v]:
8
return 'Negative cycle detected'
9
return dist
Current
Executed
Pending

Explanation

What's Happening?

Step 1/8

Initialize distances: S=0, others=∞.

Updates with each step • Clickfor full view

Code Implementation

def bellman_ford(graph, start_node):
    distances = {node: float('inf') for node in graph}
    distances[start_node] = 0
    num_vertices = len(graph)

    for _ in range(num_vertices - 1):
        for u, edges in graph.items():
            for v, weight in edges.items():
                if distances[u] != float('inf') and distances[u] + weight < distances[v]:
                    distances[v] = distances[u] + weight

    # Check for negative weight cycles
    for u, edges in graph.items():
        for v, weight in edges.items():
            if distances[u] != float('inf') and distances[u] + weight < distances[v]:
                return "Graph contains a negative weight cycle"
                
    return distances
Bellman-Ford Algorithm - Interactive Visualization | AlgoViz | AlgoViz