Description

The Bellman-Ford Algorithm is an algorithm for finding the shortest paths from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, which only works on graphs with non-negative edge weights, the Bellman-Ford algorithm can handle graphs containing negative edge weights. However, it cannot correctly produce shortest paths if the graph contains a negative-weight cycle (a cycle whose total edge weight sum is negative).

The algorithm works by iteratively relaxing all edges in the graph. It sequentially improves shortest-path estimates by checking all edges and updating vertex distances.

Steps of the Bellman-Ford Algorithm:

  1. Initialize distances: Set the distance to all vertices to infinity (∞), except for the starting vertex, which is set to 0.
  1. Edge Relaxation: For every edge (u, v) with weight w(u, v), check if the distance to vertex v can be shortened by going through vertex u:

dist[v] = min(dist[v], dist[u] + w(u, v))

  1. Repeat Relaxation: Repeat step 2 for all edges V - 1 times (where V is the number of vertices). This guarantees finding shortest paths for graphs without negative cycles.
  1. Negative Cycle Detection: After V - 1 iterations, run one more check across all edges. If any distance can still be reduced, it indicates the presence of a negative-weight cycle.

Example Output

Shortest distances from vertex 0:

  • To vertex 0: 0
  • To vertex 1: -1
  • To vertex 2: 2
  • To vertex 3: -2
  • To vertex 4: 1

Step-by-Step Explanation

  1. Initialization:

Set the distance from the starting vertex to itself as 0 and to all other vertices as infinity (∞).

  1. Edge Relaxation:

In each pass, iterate through every edge in the graph. If going through vertex u to vertex v yields a shorter path than currently known, update dist[v].

  1. Negative Cycle Verification:

After completing V - 1 iterations, check all edges once more. If a path distance can still be decreased, a negative cycle exists, and the algorithm reports it.

Python Implementation

INF = float('inf')

def bellman_ford(graph, start):
    """
    Implementation of the Bellman-Ford algorithm to find shortest paths
    from a start vertex to all other vertices in a graph.
    
    graph - list of edges represented as tuples (u, v, weight)
    start - starting vertex identifier
    
    Returns a dictionary of shortest distances from start to all vertices.
    """
    # Initialize distances
    dist = {i: INF for i in range(len(graph))}
    dist[start] = 0

    # Relax edges V - 1 times (where V is the number of vertices)
    for _ in range(len(graph) - 1):
        for u, v, weight in graph:
            if dist[u] != INF and dist[u] + weight < dist[v]:
                dist[v] = dist[u] + weight

    # Check for negative-weight cycles
    for u, v, weight in graph:
        if dist[u] != INF and dist[u] + weight < dist[v]:
            print("Graph contains a negative-weight cycle!")
            return None

    return dist

# Example usage:
# Graph represented as an edge list: (u, v, edge_weight)
graph = [
    (0, 1, -1), # Edge from vertex 0 to vertex 1 with weight -1
    (0, 2, 4),  # Edge from vertex 0 to vertex 2 with weight 4
    (1, 2, 3),  # Edge from vertex 1 to vertex 2 with weight 3
    (1, 3, 2),  # Edge from vertex 1 to vertex 3 with weight 2
    (1, 4, 2),  # Edge from vertex 1 to vertex 4 with weight 2
    (3, 2, 5),  # Edge from vertex 3 to vertex 2 with weight 5
    (3, 1, 1),  # Edge from vertex 3 to vertex 1 with weight 1
    (4, 3, -3)  # Edge from vertex 4 to vertex 3 with weight -3
]

start = 0
distances = bellman_ford(graph, start)

if distances:
    print(f"Shortest distances from vertex {start}:")
    for vertex, distance in distances.items():
        print(f"To vertex {vertex}: {distance}")

Complexity

  • Time Complexity: O(V · E), where V is the number of vertices and E is the number of edges. The algorithm performs V - 1 iterations, checking all E edges in each step.
  • Space Complexity: O(V), as it requires storing shortest distance values for all vertices in the graph.

Applications of the Bellman-Ford Algorithm

  1. Graphs with Negative Edge Weights: Unlike Dijkstra's algorithm, Bellman-Ford reliably handles graphs that contain edges with negative weights.
  2. Negative Cycle Detection: Used to detect negative cycles in graphs, which is crucial for analyzing financial systems, trade loops, and network models.
  3. Financial Modeling: Applied in foreign exchange arbitrage detection, where negative cycles correspond to profitable currency exchange loops.
  4. Graph Theory: Frequently used in theoretical computational graph problems and routing protocols (such as Distance-Vector Routing protocols like RIP).

Conclusion

The Bellman-Ford algorithm is a versatile tool for finding single-source shortest paths in graphs with arbitrary edge weights and serves as an effective mechanism for detecting negative-weight cycles.