Keep the original all-to-one orientation of the Bellman inequalities: concerns routes from to a fixed sink , and belongs to the original directed edge . Initialize and for . The synchronous dynamic programming recurrence is
It prepends the first edge of a route instead of appending the last: is the minimum cost of a directed walk from to using at most edges. In particular, improving can improve labels on incoming directed edges . The same original directed edge therefore updates its tail in this convention, whereas single-source edge relaxation updates its head.
If no negative-cost directed cycle can reach , rounds suffice for every distance to , and automatically. This hypothesis concerns directed paths from the cycle to the sink, not paths from the sink to the cycle. In the base example with its original arrows and sink , the distances in order are . Once of weight is added, instead have distance to , while keeps distance and keeps .
More generally, precisely when can reach a negative-cost directed cycle that can reach . Thus the affected vertices are the ancestors of such a directed cycle. A negative-cost directed cycle unable to reach is irrelevant. Reversing all arrows makes a single source, turns these ancestors into descendants, and makes the detection and forward graph search above directly applicable. The right panel of the figure uses that reversal with sink ; its distances to equal the left panel's distances from .
Do not force the root to remain zero outside the hypothesis. Consider the two directed edges of cost and of cost , with sink . The recurrence gives and : the latter records one lap of a negative-cost directed cycle through . Repetition makes both unrestricted distances . Clamping at zero and omitting its update would instead leave the stationary labels , concealing that behaviour. Initialization specifies the cost of the empty directed walk; it does not forbid cheaper nonempty returns to the root. Cycle detection must test every relevant directed edge, including those whose relaxation updates the root.
Bellman-Ford algorithm Created 2026-10-14 Updated 2026-10-18
The Bellman-Ford algorithm solves the single-source shortest path problem in a finite directed graph with finite real edge weights, allowing negative weights. It repeatedly applies edge relaxation, so an improved tentative distance can improve its neighbours on a later visit. This makes it a label-correcting shortest-path algorithm.[ref] If no negative-cost directed cycle is reachable from the source, at most complete passes suffice for all distances; a further check detects a reachable negative-cost directed cycle.[ref]
There are two orientations to keep distinct. The usual single-source problem asks for distances from , extending routes along outgoing directed edges. The Bellman inequalities above instead concern distances to a sink , prepending incoming directed edges to known routes. The All-to-one Bellman-Ford recurrence below preserves that convention. Reversing every directed edge, with its weight unchanged, converts one problem into the other.
Here is an original single-source example with source , vertex set , and precisely these directed edges:
The negative edge is harmless: this directed graph has no directed cycle. Its best route to is , of cost . The other routes to cost through and through .
Figure 1.
Four in-place Bellman-Ford algorithm passes propagate an improvement across a negative-weight edge
. Details.
Initialize and the other tentative distances to . In each pass apply single-source edge relaxation, , scanning in the order , , , , , . Skip a candidate with . The figure records labels after each complete pass and uses current labels immediately: it is an in-place trace. In pass 2, still uses , giving ; only later does lower to . Pass 3 carries that improvement to , and pass 4 carries it to . The final labels in order are ; the final shortest-path predecessors are for respectively.
The scan order explains the delay. Scanning instead as , , , , , gives those same final labels in just one in-place pass. The Synchronous Bellman-Ford recurrence has a precise bound on the number of edges used by a recorded route; an in-place pass can propagate along several edges and need not have that interpretation. Both implementations have the pass guarantee under the stated no-reachable-negative-cycle hypothesis.
With a stored list of edges, complete-pass Bellman-Ford algorithm has time complexity and uses extra space for labels and shortest-path predecessors, using Big O notation and constant-cost arithmetic. The extra accounts for initialization even when is empty. A pass with no strict decrease permits early termination. A queue variant instead revisits outgoing edges of vertices whose labels improved; the authored implementation provides this alternative and has worst-case running time on its usual nontrivial instances.[ref] For nonnegative weights, the Dijkstra algorithm and its existing distance-frontier figure explain how permanent labels can avoid these repeated passes; the existing edge relaxation figure illustrates one update at a time.
Bellman inequalities Created 2026-10-14 Updated 2026-10-18
The Bellman inequalities turn local directed edge checks into a global certificate for the shortest path problem. Here the convention is all-to-one: every journey ends at a fixed vertex , and is the cost of the original directed edge . Work in a finite directed graph with finite real costs. Write for candidate labels, normalized by , on the vertices that can reach . A feasible potential means precisely that these finite labels satisfy
for every directed edge within that set. These labels give lower bounds on costs to . A discovered directed path of cost instead gives an upper bound. The following constructed graph shows both bounds and the exact distances between them; its weights are illustrative costs, not measured travel data.
Figure 1.
Bellman inequalities and explicit directed paths certify distances to from opposite sides
. Details.
The arrows in the picture point toward the destination, whereas edge relaxation propagates an improved label in the opposite direction: an improved can lower . In the pictured graph, the directed paths from to cost , , and . Thus . The candidate in vertex order is feasible, but underestimates the exact distances . Merely satisfying the Bellman inequalities does not make a candidate exact.
Why do they give lower bounds? Along any directed path , successive substitution gives
The same calculation works for a directed walk, with repeated vertices allowed. Taking the infimum of route costs gives . A discovered route gives . If the bounds meet, , they certify an optimum without enumerating routes. Equivalently, check the Bellman inequalities for the proposed distances and exhibit directed paths realizing them. The authored Bellman-Ford algorithm implementation checks the corresponding single-source inequalities and equality on recorded route edges; reversing every directed edge gives this all-to-one convention.[ref]
For the exact labels in the picture, the slack is respectively on , , , , . Zero slack means equality; the zero-slack directed path realizes the cost . This is the useful beauty of the certificate: a few local inequalities rule out every cheaper journey, while one explicit journey attains the bound.
Keep unreachable vertices separate: when no directed path to exists, and a finite lower bound alone cannot certify that fact. Extended labels can use for finite , but never compute a slack as . If can reach a negative-cost directed cycle and then reach , repeatedly traversing the directed cycle makes route costs unbounded below: their infimum is , with no finite shortest directed walk. A finite feasible potential on such a directed cycle is impossible, since summing its Bellman inequalities would give . A negative-cost directed cycle that cannot reach does not affect distances to . These are statements about unrestricted directed walks; requiring a directed path with no repeated vertices is a different optimization problem when negative-cost directed cycles exist.[ref]
For the single-source convention, the same original directed edge instead gives with , a lower bound on distance from . The endpoint carrying the label on the left therefore changes with the direction of the problem.
Initialize source distance to zero and other distances to infinity, then process vertices in topological order, relaxing their outgoing edges once. Every predecessor on a path to a vertex appears earlier, so induction through that ordering proves that its distance is final when processed. Negative weights are allowed because there are no directed cycles. With adjacency lists, topological sorting and all edge relaxations take time; predecessor pointers reconstruct paths.
Dijkstra algorithm 2026-10-14
The Dijkstra algorithm solves the single-source shortest path problem in a finite graph with nonnegative edge weights, finding distances to all reachable vertices. Start with tentative distance and elsewhere. Repeatedly choose the unfinalized vertex with least tentative distance, declare that label permanent, and perform edge relaxation on its outgoing edges. For an undirected graph, inspect both directions. A finite tentative distance always records the cost of a discovered graph path, but can improve before finalization.
In our example, finalizing discovers at , at , and at . Choose next: edge relaxation through lowers to and to . Choose : edge relaxation through lowers to . Finally choose . The permanent distances are therefore , , , ; the evolving tentative distances were and .
Figure 1.
Tentative distances fall until the Dijkstra algorithm makes each label permanent
. Details.
Store a shortest-path predecessor whenever edge relaxation improves a label. The final table contains enough information to reconstruct routes, rather than merely their costs:
VertexDistance from Shortest-path predecessorFinalization order
None: source
Following shortest-path predecessors backwards gives ; reversing the order gives . If only this destination matters, stop when is finalized. Stopping when is first discovered would incorrectly return . If the smallest remaining tentative distance is , all remaining vertices are unreachable.
Why is the permanent choice safe? Suppose the selected vertex had a cheaper graph path. Let be the first unfinalized vertex on that graph path. Its preceding vertex was finalized, so edge relaxation has already offered a label no larger than that prefix's cost. Nonnegative remaining edge weights make the whole cost at least this prefix's cost; selection gives . A cheaper graph path would contradict these comparisons. Zero weights are allowed; ties can be resolved arbitrarily. This is the reason the label-setting shortest-path algorithm works, rather than a lucky feature of the drawing.
Negative weights break that reasoning. In a directed graph with costing , costing , and costing , the Dijkstra algorithm would finalize at before discovering the cheaper cost . The Bellman-Ford algorithm handles negative edge weights when no relevant negative directed cycle exists.
With an adjacency list and an indexed binary heap implementing a priority queue, the time complexity is for , using Big O notation. Each vertex is extracted at most once, each edge is inspected once per direction, and each successful edge relaxation decreases a heap key in time. This assumes constant-cost arithmetic and comparisons; exact computation with very large weights adds their representation cost. The queue uses space beyond the graph. Simply scanning all remaining vertices gives instead.[ref][ref]
The 1959 paper presents the shortest path problem as its second problem, after the minimum spanning tree problem, and grows known shortest routes in increasing distance order.[ref] In his later recollection, Dijkstra dated the shortest-route discovery to 1956: a demonstration for the ARMAC computer used a simplified Dutch railway map and printed the route between towns. A practical request became an enduring algorithm because the same distance rule applies to any suitable graph.[ref]
Edge relaxation Created 2026-10-14 Updated 2026-10-18
Edge relaxation tests whether extending a recorded route by one directed edge improves a tentative distance. For a single source and an original directed edge of weight , form the candidate . If is finite and , replace by and record the shortest-path predecessor . Otherwise leave both unchanged. The minimum formula in the header gives the resulting label in either case. The authored implementation uses this strict comparison and records the incoming directed edge.[ref]
Figure 1.
Edge relaxation lowers discovered-route costs, including across a negative-weight directed edge
. Details.
The table lists labels after each specified operation, keeping throughout this constructed acyclic graph. Relaxing first offers . Relaxing then offers , lowering from to ; revisiting now offers . Finally offers , so the label stays. Changing a label can make a previously checked outgoing directed edge worth checking again. This trace illustrates the operation itself, with a deliberately specified order, rather than a run of the Dijkstra algorithm.
A single edge relaxation does not require nonnegative weights: its candidate is the cost of a real extended directed walk, even when the last directed edge has negative weight. Nonnegative weights are needed by the Dijkstra algorithm to make its selected minimum tentative distance permanent. The Bellman-Ford algorithm permits negative weights and revisits labels; its authored implementation also checks for reachable negative-cost directed cycles.[ref][ref]
For the all-to-one convention of the Bellman inequalities, relax the same original directed edge by . This prepends to a discovered route from to , and improves the tail label , not the head label . Skip the operation when . In exact arithmetic, a full pass over all relevant directed edges with no improvement establishes all their Bellman inequalities; combined with the discovered-route upper bounds, this certifies finite distances. One unsuccessful operation establishes only that this particular candidate did not improve its label at that moment.
Use the DAG shortest-path algorithm: first compute a topological ordering, then perform edge relaxation once for every edge in that order. Store a shortest-path predecessor when a distance improves so that the actual paths, as well as their costs, can be recovered.
order := a topological ordering of V;
FOR each vertex v DO d[v] := infinity; pred[v] := NIL END;
d[source] := 0;
FOR u in order DO
  IF d[u] <> infinity THEN
    FOR each edge (u,v) with cost w DO
      IF d[u] + w < d[v] THEN
        d[v] := d[u] + w; pred[v] := u
      END
    END
  END
END
Each loop has a natural invariant. During initialization, all vertices already processed have infinite distance and no predecessor. During the outer relaxation loop, all processed vertices have their final shortest-path distances, and every edge leaving a processed vertex has been relaxed. During an inner edge loop, the outgoing edges of u already inspected have been relaxed using its final distance, while the outer invariant remains true for all earlier vertices.
For correctness, every path to a vertex ends with an edge from an earlier vertex in the topological ordering. When is reached, all those earlier distances are correct and all incoming edges have been relaxed. Therefore
with infinite distance for unreachable vertices and the empty path included at the source. No directed path can return to the source in a Directed acyclic graph. Induction over the topological ordering proves all distances correct. Following predecessor links backward reconstructs each reachable shortest path.
With adjacency lists, topological sorting takes time and the relaxation pass has the same bound, using extra space beyond the input. Thus the full distance and predecessor representation costs time. Printing every source-to-vertex path separately can take more time because their total output length may be quadratic. The stipulated nonnegative costs are sufficient; this algorithm actually also permits negative costs because there are no directed graph cycles.
Process outgoing edges in topological order:
order = topological_sort(G)
for v in V:
    distance[v] = infinity
    predecessor[v] = none
distance[s] = 0

for u in order:
    if distance[u] != infinity:
        for edge (u,v) of weight w:
            if distance[u] + w < distance[v]:
                distance[v] = distance[u] + w
                predecessor[v] = u
For correctness, argue by induction through the topological sort. Every path ending at a vertex reaches it through some incoming edge . All such predecessors occur earlier, so their finalized shortest-path distances have already been considered when is processed. Taking the minimum of over these edges therefore gives exactly the shortest-path distance to . Unreachable vertices retain infinity. Negative edge weights cause no difficulty because a later vertex cannot lead back to an earlier one.
This is the DAG shortest-path algorithm. Topological sorting and the single pass of edge relaxation each take time with adjacency lists; distances, predecessors and the order use auxiliary space. Following predecessors reconstructs a shortest path to any reachable target.
Use an indexed priority queue of unsettled vertices, keyed by their tentative distances. Initialize the source to zero and other keys to . Each ExtractMin settles the currently closest vertex. Scan its outgoing edges; whenever edge relaxation improves a neighbour's tentative distance, update that neighbour with DecreaseKey. Already settled vertices need no further update, by the correctness of Dijkstra's algorithm for nonnegative weights.
There are at most extractions and at most successful decreases. The indexed priority queue maintains each vertex's current array position and updates this index table on every swap, so locating a key for DecreaseKey costs . Preallocate capacity . Repeated insertion costs , or bottom-up heap construction initializes the queue in time. Scanning adjacency lists costs in total.
For and , the heap-operation contributions are therefore
and the overall bound is
A uniform bound including larger arity and tiny graphs is . Arity greater than the number of vertices offers no useful extra heap levels. These bounds assume adjacency lists; with an adjacency matrix, scanning neighbours contributes instead. No rebuilding of the heap is required after each decrease.
Every finite distance label is the weight of a discovered directed walk, so it can never underestimate a finite shortest-path distance. After complete passes, each label is at most the cost of every source-to-vertex path using at most edges. To prove that assertion, consider such a path's last edge : after the previous pass, already has a label no greater than the prefix cost, and the current pass relaxes that last edge. In-place improvements can only make the label smaller, preserving the assertion.
When no negative-weight cycle is reachable, any repeated-vertex portion of an optimal walk can be removed without increasing its cost. Some shortest path therefore has at most edges. The two bounds meet after that many passes, proving correctness. If a complete pass makes no change, all edge relaxation inequalities already hold and further passes cannot improve anything. A further strict relaxation after passes implies a reachable negative cycle by the same simple-path bound.
Initialize and elsewhere. Perform full passes over the directed edges, applying edge relaxation whenever is finite. For an undirected graph, process each edge in both directions. Stop early if a pass makes no change.
Each finite label records the cost of a discovered directed walk, so it never understates the true infimum. After passes, relaxation has propagated along every route of at most edges, so the label is no greater than the cost of any such route. If no reachable negative-cost closed walk exists, an optimal route can be chosen without repeated vertices and has at most edges. These inequalities prove that the final labels are the desired shortest path lengths.
An additional pass checks for an improving edge from a reachable vertex. If one exists, report a reachable negative-cost cycle: finite shortest distances cannot be assigned to vertices reachable from that cycle. Mark those vertices by forward reachability if individual answers are wanted. In particular, a reachable negative undirected edge becomes a negative two-arc closed walk under the bidirected interpretation; generic signed weights do not guarantee finite answers.
Each pass costs , giving for the usual Bellman-Ford algorithm bound. Including initialization gives , which also handles an edgeless graph honestly; these coincide in order when .
The intermediate states of the Bellman-Ford algorithm depend on edge order. Specify in-place edge relaxation in lexicographic directed-edge order:
Starting with , the first pass changes the vector as follows; omitted relaxations make no change:
The next pass makes no change, allowing early termination. If all passes are performed, passes two through four retain .
For the synchronous convention, where every relaxation reads only the previous row, the Synchronous Bellman-Ford recurrence instead gives
Both conventions reach the same shortest distances. The algorithm's eponyms are Richard Bellman and L. R. Ford Jr..
Start with . With in-place edge relaxation, the Bellman-Ford algorithm makes the following changes during its first lexicographic pass:
The next pass makes no change; any remaining fixed-count passes also make none. Thus the final vector is . These are sequential updates within a pass, rather than the simultaneous values of the Synchronous Bellman-Ford recurrence.
Shortest-path predecessor 2026-10-14
A shortest-path predecessor records the previous vertex on a chosen route from source to . When edge relaxation strictly improves through , set . For a multigraph, store the actual directed edge, since two edges with the same endpoints can have different weights. Initialize all vertices, including the source, without a shortest-path predecessor. The authored implementation reconstructs a route by following these incoming edges backwards, then reversing their order.[ref]
At the end of the edge relaxation trace, , , and . Following them gives , so the forward directed path is , of cost . This makes the distance useful: a number tells us the best cost, whereas the shortest-path predecessors tell us which connections to take. In the Dijkstra algorithm, reconstruct a destination's shortest route after its label becomes permanent. In a label-correcting shortest-path algorithm, wait for convergence and the appropriate negative-cost directed cycle check. During correction, a predecessor's label may have changed since its child's last update: immediately after in the trace, the current chain to costs although still records the earlier discovered route of cost .
Strict improvement is a useful guard against directed cycles in the recorded pointers. Consider and of cost zero, followed by and , also of cost zero. After the first two edge relaxations, both labels are zero and both shortest-path predecessors are . If equality also allows pointer replacement, the last two operations can set and : following pointers loops forever despite correct distance labels. Keeping the old pointer on ties prevents this example; choosing among equal-cost routes requires a separate rule that preserves a route to the source. Strict improvement alone does not protect against reachable negative-cost directed cycles, which can force endless decreases. Equality on recorded edges plus the Bellman inequalities certifies route costs only when the pointer chains actually terminate at the source.
For all-to-one distances to , record a next vertex whenever relaxing improves . Follow these successors forward in the original directed graph to reach . They are shortest-path predecessors when viewed in the reversed directed graph; keeping the direction convention explicit prevents returning a route whose arrows point the wrong way.
Tentative distance Created 2026-10-14 Updated 2026-10-31
A tentative distance is the cheapest cost so far recorded by a shortest path problem algorithm. For the single-source convention, initialize and elsewhere. Every finite label is the cost of a discovered route from to , so
It is an upper bound supplied by an actual route, not a guess that might be too low. The loop invariant follows directly from edge relaxation: extending a discovered route to by supplies another discovered route. The usual label initialization and this safety property are stated and proved in the authored MIT notes.[ref]
In the trace under edge relaxation, first records the direct directed path . Later records , and finally records . Each label is a usable route cost, but the first two are not shortest. An infinite tentative distance means no route has yet been discovered; only a completed search establishes unreachability. The isolated vertex in that example remains at .
In a directed graph, the discovered route is formally a directed walk, which may repeat vertices; in the pictured acyclic graph it is always a directed path. Negative-cost directed cycles can keep supplying cheaper directed walks without a finite optimum. In the all-to-one convention, the same meaning applies to discovered routes from to . Do not confuse either version with the lower bounds supplied by feasible potentials in the Bellman inequalities: one records something achievable, the other rules out anything cheaper.