Bellman-Ford Algorithm

Graph Selection

Playback Controls

Select start and target nodes to begin

Bellman-Ford Info

Key Features:

  • • Handles negative edge weights
  • • Detects negative cycles
  • • Time complexity: O(V×E)
  • • More general than Dijkstra

Legend:

Current/Start Node
Visited Nodes
Being Relaxed
Shortest Path

Reference implementation of Bellman-Ford Algorithm. Select a language tab to view and copy the code.

def bellman_ford(n: int, edges: list[tuple[int,int,int]], src: int) -> list[float]:
    dist = [float('inf')] * n
    dist[src] = 0

    # Relax all edges n-1 times
    for _ in range(n - 1):
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w

    # Detect negative-weight cycle
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            raise ValueError("Negative weight cycle detected")

    return dist

Python — Code Walkthrough

  1. float("inf") — no overflow risk

    dist = [float("inf")] * n

    Python's float('inf') + any number is still inf, so the overflow guard needed in C/Java is unnecessary. The relaxation condition dist[u] + w < dist[v] handles unreachable nodes naturally.

  2. range(n-1) for V−1 iterations

    for _ in range(n - 1)

    The loop variable is unused, so _ is the conventional placeholder. range(n-1) generates exactly n−1 iterations — the number of relaxation passes required.

  3. Tuple unpacking for edges

    for u, v, w in edges

    Each edge is a tuple (u, v, w). Python's unpacking assignment names all three components in one readable line, avoiding indexing like edge[0], edge[1], edge[2].

  4. raise ValueError on negative cycle

    raise ValueError("Negative weight cycle detected")

    Raising an exception stops execution and propagates the error. The caller decides whether to catch and handle it or let it propagate further up the call stack.