{
  "id": "bellman-ford-algorithm",
  "title": "Bellman–Ford Algorithm",
  "lang": "en",
  "source_lang": "en",
  "summary": "The Bellman–Ford algorithm computes single-source shortest paths in weighted graphs with negative edges and detects negative-weight cycles reachable from the source.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Bellman–Ford–Moore algorithm"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/bellman-ford-algorithm/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/bellman-ford-algorithm/",
      "json": "https://aiwiki.page/zh/bellman-ford-algorithm.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The Bellman–Ford algorithm is an algorithm for solving the single-source shortest-path problem in a weighted graph. Given a source vertex, it computes the minimum total edge weight needed to reach every other vertex, provided the relevant distances are not made unbounded below by a reachable negative-weight cycle. Unlike Dijkstra’s algorithm, it permits negative edge weights. Its standard implementation repeatedly relaxes all edges and can detect whether a negative-weight cycle is reachable from the source."
    },
    {
      "heading": "Problem and assumptions",
      "text": "Let \\(G=(V,E)\\) be a directed graph with a finite vertex set \\(V\\), edge set \\(E\\), and edge-weight function \\(w:E\\to\\mathbb{R}\\). Let \\(s\\in V\\) be the source.\n\nThe weight of a route is the sum of its edge weights. The shortest-path distance \\(\\delta(s,v)\\) is conventionally understood as the infimum of the weights of all directed walks from \\(s\\) to \\(v\\). Three outcomes are possible:\n\n- Finite distance: a minimum-weight route exists.\n- Unreachable vertex: no route exists, represented by \\(+\\infty\\).\n- Unbounded-below distance: a negative-weight cycle can be reached from \\(s\\), and \\(v\\) can be reached from that cycle, so repeating the cycle makes the route weight arbitrarily small. This is represented mathematically by \\(-\\infty\\).\n\nA negative-weight cycle is a directed cycle whose edge weights sum to a negative number. Negative edges alone do not prevent finite shortest paths.\n\nThe standard Bellman–Ford procedure either returns distances when no negative cycle is reachable from \\(s\\), or reports a reachable negative cycle. An extended implementation can also identify exactly which vertices have distance \\(-\\infty\\).\n\nFor an undirected graph represented by two oppositely directed edges per connection, any negative-weight edge creates a negative closed walk: it can be traversed in both directions repeatedly. Consequently, negative edges in undirected graphs require particular care when interpreting the problem."
    },
    {
      "heading": "Relaxation",
      "text": "The algorithm maintains a tentative distance \\(d[v]\\) for every vertex and, optionally, a predecessor \\(\\pi[v]\\) for reconstructing routes.\n\nInitially,\n\n\\[d[s]=0,\\qquad d[v]=+\\infty\\quad\\text{for }v\\ne s.\\]\n\nTo relax an edge \\((u,v)\\), the algorithm checks whether reaching \\(u\\) and then following that edge improves the current distance to \\(v\\):\n\n\\[\\text{if }d[u]\\ne+\\infty \\text{ and }d[u]+w(u,v)<d[v],\\]\n\nthen it sets\n\n\\[d[v]\\leftarrow d[u]+w(u,v), \\qquad \\pi[v]\\leftarrow u.\\]\n\nA relaxation never increases a tentative distance. Every finite value produced corresponds to the weight of an actual walk from the source. The difficulty is determining how many repetitions are sufficient to propagate all necessary improvements."
    },
    {
      "heading": "Dynamic-programming interpretation",
      "text": "Bellman–Ford can be understood through dynamic programming. Let \\(D_k(v)\\) be the minimum weight of a walk from \\(s\\) to \\(v\\) using at most \\(k\\) edges. Then\n\n\\[D_0(v)= \\begin{cases} 0,&v=s,\\\\ +\\infty,&v\\ne s, \\end{cases}\\]\n\nand\n\n\\[D_k(v)= \\min\\left( D_{k-1}(v), \\min_{(u,v)\\in E} \\left[D_{k-1}(u)+w(u,v)\\right] \\right).\\]\n\nA direct implementation of this recurrence uses a previous-round array and a current-round array.\n\nThe common implementation instead updates one distance array in place while scanning the edges. Consequently, an improvement may propagate through several edges during a single pass, depending on edge order. Its values after pass \\(k\\) need not equal \\(D_k(v)\\), but they are at least as good: every shortest route using at most \\(k\\) edges has been accounted for by the end of that pass.\n\nIf no negative cycle is reachable from the source, any walk can have its cycles removed without increasing its weight. A shortest route can therefore be chosen to be simple, containing at most \\(|V|-1\\) edges. This explains the algorithm’s standard pass limit."
    },
    {
      "heading": "Standard procedure",
      "text": "The following pseudocode uses in-place relaxation and stops early if an entire pass makes no change:\n\nBellmanFord(V, E, w, s):\n    for each vertex v in V:\n        d[v] = infinity\n        predecessor[v] = none\n    d[s] = 0\n\n    for i = 1 to |V| - 1:\n        changed = false\n\n        for each edge (u, v) in E:\n            if d[u] != infinity and d[u] + w(u, v) < d[v]:\n                d[v] = d[u] + w(u, v)\n                predecessor[v] = u\n                changed = true\n\n        if not changed:\n            return d, predecessor\n\n    for each edge (u, v) in E:\n        if d[u] != infinity and d[u] + w(u, v) < d[v]:\n            return \"negative-weight cycle reachable from source\"\n\n    return d, predecessor\n\nThe final scan tests for an improvement; it need not actually update the distances. Early termination is valid because a complete pass without changes establishes that every edge already satisfies its relaxation inequality.\n\nWhen finite distances have been obtained, a route to a reachable target can be reconstructed by following predecessors backward to \\(s\\) and reversing the resulting sequence."
    },
    {
      "heading": "Correctness",
      "text": "Two central properties explain the algorithm’s correctness.\n\nFirst, every finite tentative distance is the weight of some source-to-vertex walk. Thus, where the true shortest-path distance is finite, a tentative value cannot be smaller than it.\n\nSecond, after \\(k\\) complete passes, the algorithm has found values no greater than the weights of all source-to-vertex routes using at most \\(k\\) edges. This can be established inductively along each route and expressed as a loop invariant.\n\nIf no reachable negative cycle exists, each reachable vertex has a shortest simple path with at most \\(|V|-1\\) edges. After that many passes, the two properties force each tentative distance to equal the corresponding shortest-path distance.\n\nWhy an extra improvement signals a negative cycle\n\nAfter \\(|V|-1\\) passes, any remaining successful relaxation implies the existence of a reachable negative cycle. Without such a cycle, shortest simple paths would already provide the final distances.\n\nConversely, suppose a reachable negative cycle exists. All its vertices become reachable in the distance labels after enough passes. If none of its edges could be relaxed, each cycle edge would satisfy\n\n\\[d[v]\\le d[u]+w(u,v).\\]\n\nAdding these inequalities around the cycle cancels the distance terms and gives\n\n\\[0\\le \\sum_{\\text{cycle}} w(u,v),\\]\n\ncontradicting the cycle’s negative total weight.\n\nThe reachability condition matters: a negative cycle in a disconnected or otherwise unreachable part of the graph does not affect a run from \\(s\\)."
    },
    {
      "heading": "Worked example",
      "text": "Consider the directed edges\n\n\\[s\\to a:4,\\qquad s\\to b:5,\\qquad a\\to b:-2,\\qquad b\\to c:3.\\]\n\nUsing the synchronous dynamic-programming formulation, the distance table is:\n\nMaximum edges allowed | \\(s\\) | \\(a\\) | \\(b\\) | \\(c\\)\n0 | 0 | \\(+\\infty\\) | \\(+\\infty\\) | \\(+\\infty\\)\n1 | 0 | 4 | 5 | \\(+\\infty\\)\n2 | 0 | 4 | 2 | 8\n3 | 0 | 4 | 2 | 5\n\nThe shortest route to \\(c\\) is\n\n\\[s\\to a\\to b\\to c,\\]\n\nwith total weight\n\n\\[4-2+3=5.\\]\n\nAn in-place implementation may obtain these final values sooner if its edge order allows improvements to propagate within the same pass.\n\nIf an edge \\(c\\to a\\) of weight \\(-2\\) is added, then the cycle\n\n\\[a\\to b\\to c\\to a\\]\n\nhas total weight \\(-2+3-2=-1\\). Because it is reachable from \\(s\\), the distances to \\(a\\), \\(b\\), and \\(c\\) become unbounded below. The distance to \\(s\\) remains \\(0\\), because the graph provides no route from that cycle back to \\(s\\)."
    },
    {
      "heading": "Complexity and implementation issues",
      "text": "The standard algorithm makes up to \\(|V|-1\\) full edge scans and one additional detection scan. Its usual worst-case time complexity is stated as\n\n\\[O(|V||E|).\\]\n\nIncluding initialization explicitly, a bound valid even for graphs with no edges is\n\n\\[O(|V|+|V||E|).\\]\n\nAn edge-list representation is sufficient. Distance and predecessor arrays require \\(O(|V|)\\) auxiliary space, excluding storage for the graph. Storing all dynamic-programming rounds is unnecessary unless intermediate results are required.\n\nImportant implementation details include:\n\n- Infinity handling: an unreachable source endpoint must be skipped before adding an edge weight. A finite sentinel used as “infinity” must not accidentally participate in arithmetic.\n- Overflow: even when individual edge weights fit in an integer type, path sums may not.\n- Floating-point arithmetic: rounding can alter comparisons and make cycles with totals close to zero difficult to classify. Using a tolerance changes the exact mathematical detection criterion.\n- Edge order: ordering can substantially change the number of passes before convergence, although it does not change the worst-case guarantee.\n- Strict updates: predecessors should normally change only when a strictly shorter distance is found. Updating predecessors on ties can complicate reconstruction.\n\nLocating cycles and affected vertices\n\nTo extract a negative cycle, an implementation can perform actual relaxations in an additional pass and record an updated vertex. Following its predecessor pointer \\(|V|\\) times reaches a vertex on a predecessor cycle; continuing until a vertex repeats recovers the cycle, with the traversal reversed to obtain its directed order.\n\nTo identify all vertices whose distances are \\(-\\infty\\), the algorithm can collect vertices improved during the additional pass and traverse forward from them using breadth-first search or depth-first search. This marks both the reachable negative cycles and their downstream vertices. Other reachable vertices can still have finite shortest-path distances."
    },
    {
      "heading": "Applications and related algorithms",
      "text": "Difference constraints\n\nBellman–Ford can test feasibility of inequalities of the form\n\n\\[x_v-x_u\\le c_{uv}.\\]\n\nRepresent each inequality by an edge \\(u\\to v\\) of weight \\(c_{uv}\\), and add a new source with zero-weight edges to every vertex. A negative cycle indicates inconsistency, because summing the inequalities around it yields an impossible inequality. If no negative cycle exists, the computed distances provide a feasible assignment.\n\nThis connects the algorithm to mathematical optimization and constraint-based scheduling.\n\nRouting\n\nBellman–Ford’s recurrence underlies distance-vector routing. Routers exchange distance estimates with neighbors and update their estimates by combining a link cost with a neighbor’s advertised distance.\n\nSuch protocols are distributed adaptations rather than literal executions of a centralized edge-scanning program. Their behavior under network changes introduces additional issues, including routing loops and the count-to-infinity problem. This is an important application in distributed computing.\n\nReweighting and arbitrage\n\nJohnson’s algorithm uses Bellman–Ford to compute vertex potentials and detect negative cycles before reweighting a graph for repeated Dijkstra searches. The reweighted edges are nonnegative while shortest-path relationships are preserved.\n\nCurrency-exchange arbitrage can also be modeled using negative-cycle detection. Assigning an exchange rate \\(r\\) the weight \\(-\\log r\\) transforms a cycle whose rate product exceeds \\(1\\) into a negative-weight cycle. Practical models must additionally account for transaction costs, numerical precision, and execution constraints.\n\nAlternatives\n\nDijkstra’s algorithm is generally preferable when all edge weights are nonnegative. In a directed acyclic graph, topological-order relaxation finds shortest paths in \\(O(|V|+|E|)\\) time even with negative weights.\n\nQueue-based variants process vertices whose distance changes may enable further relaxations. These can avoid many unnecessary scans in practice, but the commonly used shortest-path faster algorithm variant still has worst-case \\(O(|V||E|)\\) time."
    },
    {
      "heading": "Historical development",
      "text": "The algorithm is named after Richard Bellman and Lester R. Ford Jr. Ford described a related method in 1956, and Bellman published his dynamic-programming formulation in 1958. Edward F. Moore independently presented a related shortest-path method in 1959, accounting for the alternative name Bellman–Ford–Moore algorithm.\n\nThese formulations established repeated relaxation as a central technique for shortest-path computation, connecting graph algorithms, dynamic programming, and distributed routing."
    }
  ],
  "links": [
    "algorithm",
    "shortest-path-problem",
    "graph-theory",
    "dijkstra-algorithm",
    "dynamic-programming",
    "pseudocode",
    "loop-invariant",
    "time-complexity",
    "space-complexity",
    "breadth-first-search",
    "depth-first-search",
    "mathematical-optimization",
    "distributed-computing"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}