Module contents
Lesson 19 of 33Core 115 min

Shortest paths

Study shortest paths through relaxation, from DAGs and Dijkstra to Bellman–Ford, Floyd–Warshall and Johnson, including recent complexity results.

After this lesson you can

  • Prove relaxation properties and Dijkstra's correctness by induction.
  • Implement Dijkstra with indexed and lazy heaps, and the 0–1 weight case with a deque.
  • Detect and extract a negative cycle with Bellman–Ford.
  • Compute all-pairs shortest paths with Floyd–Warshall and Johnson and choose by density.
  • Explain the contribution of recent single-source shortest-path results.

Before you start

Motivation: the same operation in four disguises

Given a directed graph with weighted edges, shortest paths asks for the minimum-total-weight path from source ss to each vertex. It looks like a map problem, and it is, but appears where no one sees a map:

  • Routing. Link-state protocols (OSPF, IS-IS) have each router reconstruct the network graph and run Dijkstra on it to decide the outgoing interface for each packet. Weights are configurable link costs, nonnegative by construction.
  • Project planning. In a project with dependent tasks, minimum duration is the dependency graph’s longest path (critical path), computed using the same technique as shortest paths in a DAG.
  • Data geometry. Isomap replaces straight-line distance between points with shortest distance inside a neighbor graph, measuring separation along the manifold containing the data. Its central step is Dijkstra from every point. You will do this in the second lab.
  • Finance. A currency-exchange cycle ending with more money than it began with is a negative-weight cycle in a graph with weights −ln⁡(tasa)-\ln(\text{tasa}). Detecting it is exactly the task Bellman–Ford solves and Dijkstra does not (arbitrage in the finance module).

Three of these four problems have negative weights or ask for maxima instead of minima, separating algorithms. The central idea: all shortest-path algorithms do the same thing and differ only in order. They relax edges; the design question is which order minimizes visits to each edge. Topological order needs one pass (DAG). Increasing distance needs one pass if weights are nonnegative (Dijkstra). Generally repeat V−1V - 1 times (Bellman–Ford). For all pairs, order shifts to intermediate vertices (Floyd–Warshall), or change the graph to use Dijkstra from each vertex (Johnson). Finally, two recent results say what can and cannot be expected of Dijkstra.

Weights, distances and relaxation

Let G=(V,E)G = (V, E) be a directed graph with weight function w:E→Rw : E \to \R, with n=∣V∣n = \abs{V} and m=∣E∣m = \abs{E} (in costs we conventionally write VV and EE for ∣V∣\abs{V} and ∣E∣\abs{E}). The weight of a path p=(v0,v1,…,vk)p = (v_0, v_1, \dots, v_k) is w(p)=∑i=1kw(vi−1,vi)w(p) = \sum_{i=1}^{k} w(v_{i-1}, v_i).

Distinguish the two infinities: +∞+\infty means “no path” and −∞-\infty means “no best path”. If no negative cycle is reachable from ss, the infimum is attained by a simple path (at most V−1V - 1 edges): removing a nonnegative-weight cycle cannot worsen a walk. Unless stated otherwise, that is the setting.

Proof

If a lower-weight path from viv_i to vjv_j existed, substituting it in pp would give a walk from v0v_0 to vkv_k of lower weight than w(p)w(p), contradicting minimality of pp.

∎

This gives the triangle inequality: for every edge (u,v)(u, v), δ(s,v)≤δ(s,u)+w(u,v)\delta(s, v) \le \delta(s, u) + w(u, v), since a shortest path to uu followed by the edge is a walk to vv. A correct distance vector must satisfy this on every edge, and the next algorithm tries to achieve it by repeated application.

Relaxation properties make every order of relaxations safe (never producing a false estimate) and some orders sufficient.

Proof

(1) Induct on the number of relaxations. Initially d[s]=0≥δ(s,s)d[s] = 0 \ge \delta(s, s) (the empty path weighs 00, so δ(s,s)≤0\delta(s,s) \le 0) and the rest equal ∞\infty. If relaxation sets d[v]=d[u]+w(u,v)d[v] = d[u] + w(u, v), then d[v]=d[u]+w(u,v)≥δ(s,u)+w(u,v)≥δ(s,v)d[v] = d[u] + w(u,v) \ge \delta(s, u) + w(u, v) \ge \delta(s, v) by induction and triangle inequality. Since dd only decreases and never below δ\delta, a value equal to δ\delta remains fixed.

(2) After relaxation, d[v]≤d[u]+w(u,v)=δ(s,u)+w(u,v)=δ(s,v)d[v] \le d[u] + w(u, v) = \delta(s, u) + w(u,v) = \delta(s, v), where the final equality is optimal substructure (the path to uu prefixes a shortest path to vv). By (1), d[v]=δ(s,v)d[v] = \delta(s, v).

(3) Induct on ii: after relaxing (vi−1,vi)(v_{i-1}, v_i), d[vi]=δ(s,vi)d[v_i] = \delta(s, v_i). For i=0i = 0, d[s]=0=δ(s,s)d[s] = 0 = \delta(s,s). The step uses (2) and the fact that by (1), d[vi−1]d[v_{i-1}] no longer changes.

∎

The third property will be used in every proof. No matter what else happens between them, if every shortest path has its edges relaxed in order, distances are correct. Algorithms differ in how they guarantee that order simultaneously for every shortest path without knowing them.

One piece remains: predecessor π\pi. The predecessor subgraph has edges (π[v],v)(\pi[v], v) for vv with π[v]\pi[v] defined. A simple invariant governs it: if π[v]=u\pi[v] = u, then d[v]≥d[u]+w(u,v)d[v] \ge d[u] + w(u, v) at all times. When π[v]=u\pi[v] = u is set there is equality, and afterward d[u]d[u] can only decrease while d[v]d[v] does not change as long as π[v]\pi[v] remains uu.

Proof

Let c=(v0→v1→⋯→vk=v0)c = (v_0 \to v_1 \to \dots \to v_k = v_0) be a cycle with π[vi]=vi−1\pi[v_i] = v_{i-1}. All its vertices have finite dd. Consider when its last edge was set, say (vk−1,vk)(v_{k-1}, v_k): just before, relaxation improved, so d[vk]>d[vk−1]+w(vk−1,vk)d[v_k] > d[v_{k-1}] + w(v_{k-1}, v_k) (strict inequality), while for the other already-present cycle edges d[vi]≥d[vi−1]+w(vi−1,vi)d[v_i] \ge d[v_{i-1}] + w(v_{i-1}, v_i) holds. Summing the kk inequalities cancels the d[⋅]d[\cdot] terms (each cycle vertex appears once on each side), leaving 0>w(c)0 > w(c).

∎

Thus if no reachable negative cycles exist, the predecessor subgraph is acyclic; since ss is the only vertex with finite dd and no predecessor (every other obtained its value by relaxation), every predecessor chain ends at ss and the subgraph is a tree rooted at ss. When d=δd = \delta everywhere it is a shortest-path tree rooted at ss: every tree path from ss is shortest. Thus algorithms return dd and π\pi together: dd is the distance table and π\pi reconstructs paths.

Paths in a DAG: an order needing one pass

The simplest relaxation order is for an acyclic graph. A DAG has a topological order in which every path visits vertices in increasing order. Processing vertices in that order and relaxing outgoing edges makes the third relaxation property hold for every path at once.

Proof

A DAG has no cycles, so every distance is finite or +∞+\infty and every shortest path p=(s=v0,…,vk)p = (s = v_0, \dots, v_k) is simple. In topological order, v0v_0 precedes v1v_1, which precedes v2v_2, and so on. Processing vi−1v_{i-1} relaxes (vi−1,vi)(v_{i-1}, v_i), and these relaxations occur in order pp. By path relaxation, d[vk]=δ(s,vk)d[v_k] = \delta(s, v_k). If vv is unreachable, d[v]d[v] never changes and equals ∞=δ(s,v)\infty = \delta(s, v).

∎

This is cheap because distance order is unnecessary for correct relaxation: an order respecting dependencies suffices. Nowhere do we use positive weights, so negative weights pose no problem in a DAG.

Longest path. Finding the longest simple path in an arbitrary graph is NP-hard, but trivial in a DAG: change min⁡\min to max⁡\max and the same traversal computes the highest-weight path (equivalent to negating all weights, with negative weights harmless in a DAG). With task durations as edge weights, the longest start-to-finish path is minimum project duration, and its critical tasks cannot be delayed. The lab computes the critical path of a six-milestone project.

There is a deeper interpretation. Recurrence d[v]=min⁡(u,v)∈E(d[u]+w(u,v))d[v] = \min_{(u,v) \in E} (d[u] + w(u,v)) is dynamic programming whose subproblem graph is the graph itself, evaluable in topological order precisely because it is acyclic. The same scheme with (min⁡,+)(\min, +) replaced by other operators is semiring dynamic programming. When the graph has cycles, the recurrence is circular and requires either an order undoing circularity (Dijkstra) or iteration to a fixed point (Bellman–Ford).

Dijkstra: the frontier advances by distance

Without negative cycles we can do better than iteration. Dijkstra’s idea is that if all weights are nonnegative, the unsettled vertex with smallest estimate already has its final distance: any other path to it must pass through another unsettled vertex whose estimate is no smaller, and can only add from there. Settle that vertex, relax its edges, repeat. This is a greedy algorithm: it picks the nearest vertex and never revisits it.

The interactive runs event by event. Each heap extraction settles a vertex; each relaxation examines an edge. The table’s “true distance” row is computed by Bellman–Ford so you can check at each step whether Dijkstra’s settled values are correct.

InteractiveDijkstra's frontier
42137261s0a∞b∞c∞d∞t∞
  • settled
  • in the heap (frontier)
  • settled at the wrong distance
  • predecessor tree
  • edge being relaxed
Heap (lowest key first):s:0
sabcdt
tentative d0∞∞∞∞∞
statefrontier·····
true distance032689
step 0 / 15
Initial state: d(s)=0d(s) = 0 and all others are ∞\infty. The heap contains only the source. Press play or advance one step at a time.
Heap
0
Extractions0
Stale entries0
Relaxed edges0
Settled with incorrect distance0
Invariantholds
Play the positive-weight graph: blue vertices are settled, yellow are frontier (in the heap), and the heap shows their keys. Then choose ‘One negative weight’: the invariant breaks when aa is settled at a distance that is not yet true (the ‘Invariant’ indicator marks it); a few steps later the path via bb exposes this, aa does not return to the heap and successors remain wrong. Try the ‘Lazy’ heap (keys do not decrease; stale entries accumulate) and enable ‘Reopen settled vertices’, which fixes the result but takes more extractions. Click any edge and adjust its weight. The negative-cycle graph does not terminate with reopening: it stops after 240 steps.

What you should see with positive weights: each vertex is extracted once in increasing distance order (s,b,a,c,d,ts, b, a, c, d, t with distances 0,2,3,6,8,90, 2, 3, 6, 8, 9), and frontier estimates fall as the frontier advances (for example aa falls from 44 to 33 when bb is extracted and b→ab \to a relaxed). The first proof step describes the state as an invariant.

Proof

Initially S=∅S = \varnothing and both conditions hold: d[s]=0d[s] = 0 and the rest is ∞\infty. The first iteration extracts ss (the only vertex with finite dd), with d[s]=0=δ(s,s)d[s] = 0 = \delta(s, s) (with w≥0w \ge 0 there are no negative cycles). Now assume both conditions hold with s∈Ss \in S, and u∉Su \notin S is extracted with finite d[u]d[u] minimum among unsettled vertices. Prove d[u]=δ(s,u)d[u] = \delta(s, u).

Let PP be a shortest path from ss to uu (it exists: finite d[u]d[u] means uu is reachable, and with w≥0w \ge 0 there are no negative cycles). By the upper bound, d[u]≥δ(s,u)d[u] \ge \delta(s,u). Let yy be the first vertex of PP outside SS (it exists since u∉Su \notin S), and xx its predecessor in PP, in SS (the first vertex of PP is s∈Ss \in S). By (I1), d[x]=δ(s,x)d[x] = \delta(s, x), and by (I2) d[y]≤d[x]+w(x,y)=δ(s,x)+w(x,y)=δ(s,y)d[y] \le d[x] + w(x, y) = \delta(s, x) + w(x, y) = \delta(s, y), with the final equality from optimal substructure. Since d[y]≥δ(s,y)d[y] \ge \delta(s, y), d[y]=δ(s,y)d[y] = \delta(s, y). Now use nonnegative weights: the prefix of PP through yy weighs no more than PP, so δ(s,y)≤δ(s,u)\delta(s, y) \le \delta(s, u). Combining everything, and with uu from minimum dd,

d[u]≤d[y]=δ(s,y)≤δ(s,u)≤d[u],d[u] \le d[y] = \delta(s, y) \le \delta(s, u) \le d[u],

so d[u]=δ(s,u)d[u] = \delta(s, u) and (I1) remains true after adding uu to SS. For (I2), relaxing uu‘s edges changes each d[v]d[v] to min⁡(d[v],d[u]+w(u,v))\min(d[v], d[u] + w(u, v)), exactly the (I2) minimum with S∪{u}S \cup \{u\} instead of SS.

Each iteration settles a vertex, so the algorithm terminates. On termination vertices outside SS have d=∞d = \infty, and by (I2) no edge leaves SS for them: they are unreachable from s∈Ss \in S, and ∞=δ\infty = \delta.

∎

The proof reveals what fails with negative weights: “the prefix weighs no more than PP” is the only line using w≥0w \ge 0. With a negative weight, a path through an unsettled vertex can end up shorter. The interactive’s minimal counterexample: s→as \to a with weight 33, s→bs \to b with 44, b→ab \to a with −2-2 and a→ca \to c with 22. Dijkstra extracts aa with d=3d = 3 and leaves d[c]=5d[c] = 5; then extracts bb, relaxes b→ab \to a and d[a]d[a] falls to 22, but aa was settled, does not return to the heap, and cc remains 55 when δ(s,c)=4\delta(s, c) = 4. There is no error signal: the algorithm terminates and returns a normal-looking table.

Which heap and at what cost

The algorithm performs VV extractions and examines every edge once; each examination may lower an estimate. Priority-queue structure determines cost:

  • Indexed binary heap (decrease-key in O(log⁡V)\bigO(\log V)): VV extractions and at most EE key decreases, O((V+E)log⁡V)\bigO((V + E) \log V) total. An index of each vertex’s position is needed.
  • Lazy insertion: do not decrease keys; each improvement inserts a new (d,v)(d, v) entry, discarding old entries upon extraction (dd greater than d[v]d[v]). The heap has at most EE entries and costs O(Elog⁡E)=O(Elog⁡V)\bigO(E \log E) = \bigO(E \log V). Simpler and almost always equally fast because few relaxations improve: in the lab only about 29% of random-graph edges improve. Forgetting to discard stale entries is the classic error: the result remains correct, but each vertex is reexpanded once per heap entry, and work changes from scanning each adjacency list once (EE edges) to up to ∑vgrado de entrada(v)⋅grado de salida(v)\sum_v \text{grado de entrada}(v) \cdot \text{grado de salida}(v).
  • Fibonacci heap (decrease-key in amortized O(1)\bigO(1), extract-min in amortized O(log⁡V)\bigO(\log V)): O(E+Vlog⁡V)\bigO(E + V \log V). This is the classical theoretical bound, though constants make it rarely competitive in practice. An dd-ary heap of d=max⁡(2,E/V)d = \max(2, E/V) gives O(Elog⁡2+E/VV)\bigO(E \log_{2 + E/V} V) (Johnson, 1977), already linear for dense graphs.
  • Small-weight graphs (next section): buckets or deque.

The Ω(Vlog⁡V)\Omega(V \log V) comparison sorting lower bound explains why Vlog⁡VV \log V appears throughout: Dijkstra extracts vertices in increasing distance order, sorting them by distance, which costs Ω(Vlog⁡V)\Omega(V \log V) in the comparison model. This is the “sorting barrier” of the final section.

Two practical observations. If only destination tt matters, stop when tt is extracted: its distance is final by (I1), avoiding the rest of the graph. Dijkstra from ss with this stopping condition is precisely uniform-cost search; potentials guiding search toward the destination give A*, discussed with Johnson.

Reopening vertices: when greedy becomes iteration

A tempting variant for negative weights: when relaxation improves a settled vertex, reinsert it into the heap and expand it again. The interactive implements this with “Reopen settled vertices”. Without negative cycles it terminates correctly: when the heap empties, every edge satisfies d[v]≤d[u]+w(u,v)d[v] \le d[u] + w(u, v) because each decreased vertex is reexpanded; summing inequalities along a shortest path gives d≤δd \le \delta and, with the upper bound, d=δd = \delta. But the greedy guarantee disappears: no longer “one extraction per vertex”, extractions can exceed VV and known negative-weight graph families force exponentially many extractions (Johnson, 1973). With a reachable negative cycle it never terminates. It is a label-correcting algorithm, Bellman–Ford’s family, rather than label-setting.

The first two variants exploit small integer weights to avoid a heap.

Dial (buckets). For integer weights in {0,…,C}\{0, \dots, C\}, tentative estimates always lie in window [k,k+C][k, k + C], where kk is the distance being settled. Store vertices in C+1C + 1 circular buckets; bucket jj contains vertices with d≡j(modC+1)d \equiv j \pmod{C+1}, and traverse k=0,1,2,…k = 0, 1, 2, \dots emptying each bucket. Cost is O(E+VC)\bigO(E + V C): at most O(VC)\bigO(VC) empty buckets are visited (maximum distance at most (V−1)C(V-1)C) and EE relaxations performed.

0–1 BFS. For weights in {0,1}\{0, 1\}, replace the priority queue with a deque: an edge of weight 00 inserts the neighbor at the front, weight 11 at the back. This works because queue keys remain ordered and in {D,D+1}\{D, D+1\}, where DD is the front vertex’s distance: on extracting a vertex with d=Dd = D, front insertions have key DD and back insertions D+1D + 1, preserving order. This is Dijkstra with a structure extracting the minimum in O(1)\bigO(1), giving O(V+E)\bigO(V + E). It illustrates avoiding the sorting barrier when keys have a small range. You implement it in an exercise.

Bidirectional search. For query s→ts \to t run two Dijkstras, one from ss on GG and one from tt on the reverse graph, alternating by smallest top key. Maintain μ\mu, the best path seen, updated at each examined edge using μ←min⁡(μ,df(u)+w(u,v)+db(v))\mu \leftarrow \min(\mu, d_f(u) + w(u,v) + d_b(v)). The correct stopping condition is not “the frontiers meet”, but cimaf+cimab≥μ\text{cima}_f + \text{cima}_b \ge \mu.

Proof

Since μ\mu is the weight of a real path, μ≥δ(s,t)\mu \ge \delta(s, t). Suppose a path PP from ss to tt has weight L<μ≤cimaf+cimabL < \mu \le \text{cima}_f + \text{cima}_b. By Dijkstra correctness, every vertex with δ(s,v)<cimaf\delta(s, v) < \text{cima}_f is settled forward with df=δ(s,v)d_f = \delta(s, v), and every vertex with δ(v,t)<cimab\delta(v, t) < \text{cima}_b is settled backward with db=δ(v,t)d_b = \delta(v,t). Traverse PP and let ℓ(v)\ell(v) be the prefix weight through vv and r(v)=L−ℓ(v)r(v) = L - \ell(v) the suffix weight. Since L<cimaf+cimabL < \text{cima}_f + \text{cima}_b, there is an edge (u,v)(u, v) of PP with ℓ(u)<cimaf\ell(u) < \text{cima}_f and r(v)<cimabr(v) < \text{cima}_b: if vv is the first vertex of PP with ℓ(v)≥cimaf\ell(v) \ge \text{cima}_f, then r(v)=L−ℓ(v)≤L−cimaf<cimabr(v) = L - \ell(v) \le L - \text{cima}_f < \text{cima}_b, and its predecessor uu satisfies ℓ(u)<cimaf\ell(u) < \text{cima}_f. Then uu is settled forward with df(u)≤ℓ(u)d_f(u) \le \ell(u) and vv backward with db(v)≤r(v)d_b(v) \le r(v). Edge (u,v)(u, v) is examined when the latter is settled (from uu in forward search or vv backward), updating μ\mu with a value ≤ℓ(u)+w(u,v)+r(v)=L\le \ell(u) + w(u,v) + r(v) = L. Then μ≤L\mu \le L: contradiction. Two edge cases remain, using that df(s)=0d_f(s) = 0 and db(t)=0d_b(t) = 0 hold from the start: if no vertex of PP has ℓ≥cimaf\ell \ge \text{cima}_f, all are settled forward, in particular the penultimate uu, and examining (u,t)(u, t) gives μ≤df(u)+w(u,t)+0≤L\mu \le d_f(u) + w(u, t) + 0 \le L; if the first with ℓ≥cimaf\ell \ge \text{cima}_f is ss itself (i.e. cimaf=0\text{cima}_f = 0), its successor vv on PP has r(v)≤L<cimabr(v) \le L < \text{cima}_b, is settled backward, and examining (s,v)(s, v) from vv gives μ≤0+w(s,v)+db(v)≤L\mu \le 0 + w(s, v) + d_b(v) \le L.

∎

The proof assumes heap tops are current entries; in the lab’s lazy version, a stale top key cannot exceed the smallest current key, so the loop condition is more conservative and merely delays stopping. The lab checks the result against Dijkstra on 40 random pairs. Each frontier explores a ball of half the radius: in a planar geometric graph, two balls of radius r/2r/2 have half the area of one of radius rr.

Bellman–Ford: iterate to a fixed point

With negative weights, increasing distance order fails, but a much coarser order works: relax all edges, again and again. A simple shortest path has at most V−1V - 1 edges, and every full edge pass relaxes at least one more edge of each shortest path.

The interactive shows synchronous rounds: each reads only the previous round’s distances (the lab code relaxes in place, converging no later; discussed below). This makes the central property visible:

Proof

Induct on kk. For k=0k = 0 only ss has value 00. A walk from ss to vv with at most kk edges either has at most k−1k - 1 (weight at least dk−1(v)d_{k-1}(v)), or exactly kk: its final edge is some (u,v)(u, v) and the rest a walk to uu with k−1k - 1 edges, weighing at least dk−1(u)d_{k-1}(u). Thus the minimum is min⁡(dk−1(v),min⁡(u,v)dk−1(u)+w(u,v))\min\big(d_{k-1}(v), \min_{(u,v)} d_{k-1}(u) + w(u,v)\big), exactly what the synchronous round computes. In-place relaxations may read current-round values, which are no larger, so the upper bound remains; the lower bound is relaxation property 1.

∎

Corollary. Without reachable negative cycles, shortest paths are simple, have at most V−1V - 1 edges, and after V−1V - 1 rounds d=δd = \delta. One more round changes nothing.

InteractiveBellman–Ford rounds and negative cycles
32−4146s0a∞b∞c∞d∞
  • distance changes this round
  • predecessor tree
  • extracted negative cycle
roundtrue
s0000000
a∞333333
b∞655555
c∞421111
d∞∞53222
round 0 / 5
Round 0: only the source has finite distance (d(s)=0d(s) = 0). Each round relaxes every edge once using only distances from the previous round.
0
Round kk0 of 5
Distances that change0
Last round with changes4
Vertices at their true distance1 of 5
Negative cycleno
Advance round by round in the graph without a negative cycle and compare each table column to paths with at most kk edges: distance to dd appears in round 2 and falls in rounds 3 and 4, because the shortest path s→a→b→c→ds \to a \to b \to c \to d has 4 edges. Switch to the negative-cycle graph (b→c→d→bb \to c \to d \to b, weight −1-1): round 5 still changes values and the figure highlights the cycle extracted via predecessor pointers. Click d→bd \to b and change its weight: the cycle ceases to be negative at 33 or more.

Detecting and extracting negative cycles

Proof

(⇐\Leftarrow) Without reachable negative cycles, after V−1V - 1 rounds d=δd = \delta, and property 1 prevents further decreases. (⇒\Rightarrow) If round VV changes nothing, d[v]≤d[u]+w(u,v)d[v] \le d[u] + w(u, v) for every edge with reachable uu. Let c=(v0,…,vk=v0)c = (v_0, \dots, v_k = v_0) be a reachable cycle: all its vertices have finite dd and summing d[vi]≤d[vi−1]+w(vi−1,vi)d[v_i] \le d[v_{i-1}] + w(v_{i-1}, v_i) around it gives 0≤w(c)0 \le w(c). Thus the cycle is not negative.

∎

Existence alone is not enough: we want the cycle, obtained from predecessors.

Proof

If xx‘s predecessor chain terminated (at a vertex without predecessor, which can only be ss), it would be a simple path p=(s=p0,…,pj=x)p = (s = p_0, \dots, p_j = x) with j≤V−1j \le V - 1 and, summing the predecessor invariant along pp (with d[s]=0d[s] = 0 because ss has no predecessor), d[x]≥w(p)≥mV−1(x)d[x] \ge w(p) \ge m_{V-1}(x), where mV−1(x)m_{V-1}(x) is the minimum weight of a walk from ss to xx with at most V−1V - 1 edges. But by the round invariant xx after round V−1V - 1 was already at most mV−1(x)m_{V-1}(x), and decreased in round VV, so d[x]<mV−1(x)d[x] < m_{V-1}(x): contradiction. The chain does not terminate, and since there are VV vertices, after VV backward steps it enters a cycle. The lemma says that cycle is negative.

∎

The lab implements exactly this and checks, on a graph with a changed weight, that the extracted cycle has negative weight.

SPFA and why the typical case is no guarantee

SPFA (Shortest Path Faster Algorithm) is Bellman–Ford with a queue: a vertex enters whenever its estimate decreases (unless already queued), and only outgoing edges of dequeued vertices are relaxed. On random graphs it is often much faster than O(VE)\bigO(VE), explaining its reputation. But its worst case remains Θ(VE)\Theta(VE), and simple inputs trigger it. The lab shows a complete DAG of nn vertices with edges listed in the wrong order: SPFA extracts (n2)+1\binom{n}{2} + 1 vertices and examines on the order of n3/6n^3/6 edges, i.e. Θ(VE)\Theta(VE) with E=(n2)E = \binom{n}{2}, while topological relaxation on the same graph relaxes each edge once. The typical case is no guarantee, especially for adversarially controlled input.

Arbitrage: a negative cycle with money

A currency market has exchange rate rijr_{ij} from ii to jj (units of jj per unit of ii). Trading around cycle i0→i1→⋯→i0i_0 \to i_1 \to \dots \to i_0 multiplies capital by ∏rikik+1\prod r_{i_k i_{k+1}}; arbitrage occurs when the product exceeds 11. Taking negative logarithms, wij=−ln⁡rijw_{ij} = -\ln r_{ij}, a product above 11 becomes a weight sum below 00: a negative cycle. Technical detail: no source necessarily reaches every cycle, so add a virtual source with edges of weight 00 to every currency, as in Johnson.

InteractiveCurrency arbitrage
EURUSDGBPJPY
  • arbitrage cycle (product of rates > 1)
  • edge weight: −ln⁡(r⋅(1−fee))-\ln(r \cdot (1 - \text{fee}))
1 unit of ↓EURUSDGBPJPY
EUR·
USD·
GBP·
JPY·
Calculando…
+0.60 %
0.10 %
Cycle found…
Gain per cycle…
Cycle weight ∑−ln⁡r\sum -\ln r…
Starting capital of 10,000…
Bellman–Ford rounds…
The rate table is consistent: rijr_{ij} is a ratio of invented prices (not market quotes). Introduce an inconsistency in one pair and Bellman–Ford finds a cycle and gain per round. Increase commission: arbitrage disappears when the deviation no longer covers cycle transaction costs (more edges mean more commission). Edit table cells to create your own opportunities. The algorithm returns some negative-weight cycle, not necessarily the most profitable.

Notice the figure’s model–reality relationship. With consistent rates and no commission, each cycle has exactly product 11 and weight sum 00: no negative cycle exists, and Bellman–Ford stops in round 22 or shortly after. Bias 0.6 %0.6\,\% in one pair creates gain, consumed by transaction commissions. Real markets also have latency, finite liquidity and slippage, ignored by this model: the algorithm detects table inconsistency and does not guarantee an exploitable trade.

All pairs

For all-pairs distances, either run a single-source algorithm from each vertex or solve everything at once.

Floyd–Warshall

Number vertices 1,…,n1, \dots, n and assume no loops (i,i)(i, i) (a negative one is already a negative cycle; a nonnegative one is useless). Let D(k)[i][j]D^{(k)}[i][j] be the best path weight from ii to jj whose intermediate vertices belong to {1,…,k}\{1, \dots, k\}. Floyd–Warshall dynamic programming uses recurrence

D(0)[i][j]={0i=jw(i,j)(i,j)∈E∞en otro caso,D(k)[i][j]=min⁡(D(k−1)[i][j],  D(k−1)[i][k]+D(k−1)[k][j]).D^{(0)}[i][j] = \begin{cases} 0 & i = j \\ w(i,j) & (i,j) \in E \\ \infty & \text{en otro caso,} \end{cases} \qquad D^{(k)}[i][j] = \min\big(D^{(k-1)}[i][j],\; D^{(k-1)}[i][k] + D^{(k-1)}[k][j]\big).

Proof

Induct on kk. A simple shortest path from ii to jj with intermediates in {1,…,k}\{1,\dots,k\} either avoids kk (weight D(k−1)[i][j]D^{(k-1)}[i][j]) or visits kk exactly once and splits into paths i⇝ki \leadsto k and k⇝jk \leadsto j, both with intermediates in {1,…,k−1}\{1, \dots, k-1\} and shortest by optimal substructure. This yields the second term. For negative cycles prove something stronger by the same induction: for every simple path or simple cycle PP from ii to jj with intermediates in {1,…,k}\{1, \dots, k\}, D(k)[i][j]≤w(P)D^{(k)}[i][j] \le w(P) holds. If PP avoids kk, use the hypothesis for k−1k - 1 and D(k)≤D(k−1)D^{(k)} \le D^{(k-1)}; if it visits kk, split it into two simple pieces with intermediates ≤k−1\le k - 1. Now let CC be a negative simple cycle and ii its greatest-index vertex. Its other vertices are below ii, and CC is a “path” from ii to ii with intermediates in {1,…,i−1}\{1, \dots, i-1\}, so D(i−1)[i][i]≤w(C)<0D^{(i-1)}[i][i] \le w(C) < 0. Conversely every DD value is the weight of a walk, so D[i][i]<0D[i][i] < 0 is a negative closed cycle.

∎

Cost is Θ(V3)\Theta(V^3) time and Θ(V2)\Theta(V^2) memory (DD can be overwritten in place because while D[k][k]=0D[k][k] = 0, i.e. without negative cycles through kk, row and column kk do not change during iteration kk; with negative cycles, the in-place version still marks them on the diagonal). The inner loop is useful: iteration kk is an outer sum of column kk and row kk followed by an elementwise minimum, one NumPy line, np.minimum(D, D[:, k:k+1] + D[k:k+1, :], out=D). Vectorization makes the difference between a usable and unusable Python algorithm, measured in the lab. Algebraically, matrix product with (min⁡,+)(\min, +) instead of (+,×)(+, \times) gives fixed-edge-count paths, and squaring ⌈log⁡2V⌉\lceil \log_2 V \rceil times computes all pairs in O(V3log⁡V)\bigO(V^3 \log V), worse than Floyd–Warshall but within semiring dynamic programming.

Johnson: change the graph to use Dijkstra

For a sparse graph, VV Dijkstra runs cost O(V(E+Vlog⁡V))\bigO(V(E + V \log V)), much less than V3V^3. Negative weights are the obstacle. Johnson’s idea is to transform them.

Proof

(1) This is feasibility: w′(u,v)=w(u,v)+h(u)−h(v)≥0w'(u, v) = w(u,v) + h(u) - h(v) \ge 0. (2) Sum ∑(w+h(vi−1)−h(vi))\sum (w + h(v_{i-1}) - h(v_i)) along pp telescopes, leaving w(p)+h(v0)−h(vk)w(p) + h(v_0) - h(v_k). (3) All paths from ss to tt change by the same constant h(s)−h(t)h(s) - h(t), so minimizing w′w' and ww gives the same minimizers. For a cycle s=ts = t and the constant is 00. Finally qq reaches every vertex and δ(q,⋅)\delta(q, \cdot) is finite iff no negative cycles exist (the only cycles are those of GG, since no edge enters qq), and triangle inequality δ(q,v)≤δ(q,u)+w(u,v)\delta(q, v) \le \delta(q, u) + w(u,v) gives feasibility.

∎

Johnson’s algorithm is then: Bellman–Ford from qq (O(VE)\bigO(VE)), reweight, Dijkstra from each vertex with w′w', undo the change with δ(u,v)=δ′(u,v)−h(u)+h(v)\delta(u, v) = \delta'(u, v) - h(u) + h(v). Fibonacci heap cost O(VE+V2log⁡V)\bigO(VE + V^2 \log V), binary heap O(VElog⁡V)\bigO(VE \log V).

InteractiveFloyd–Warshall and Johnson
47−32631−45abcde
  • already allowed intermediate vertex
  • newly allowed vertex
from ↓ to →abcde
a047∞−3
b∞0∞26
c∞30∞∞
d1∞−40∞
e∞∞∞50
D(0)
Matrix D(0)\mat{D}^{(0)} contains direct edge weights, 0 on the diagonal, and ∞\infty where there is no edge. No intermediate vertices are allowed.
Algorithm
0
Allowed intermediate vertices0 of 5
Changing entries0
Negative cycle (at the end)no
In ‘Floyd–Warshall’, advance with the player: each step admits one more intermediate vertex and orange cells improve. In ‘Johnson’, potentials hh are computed with Bellman–Ford and each edge shows its original and new nonnegative weight (aquamarine for 00). Choose source and destination to see the shortest path is unchanged under ww and w′w' and its length changes by h(origen)−h(destino)h(\text{origen}) - h(\text{destino}). Click an edge and lower its weight until it creates a negative cycle: the Floyd–Warshall matrix diagonal becomes negative and Johnson stops.

Which to choose? In a dense graph, with E=Θ(V2)E = \Theta(V^2), Floyd–Warshall costs Θ(V3)\Theta(V^3) and Johnson too (O(V3)\bigO(V^3) with Fibonacci, O(V3log⁡V)\bigO(V^3 \log V) with binary heap), so Floyd–Warshall wins on simplicity and vectorization. On sparse graphs Johnson clearly wins (V2log⁡VV^2 \log V versus V3V^3). If weights are already nonnegative, neither Bellman–Ford nor reweighting is needed: VV Dijkstra runs. With V=105V = 10^5 the result matrix itself does not fit (101010^{10} entries); request rows or only necessary queries.

Reweighting recurs elsewhere. A* search is Dijkstra on the graph reweighted by w′(u,v)=w(u,v)+π(v)−π(u)w'(u,v) = w(u,v) + \pi(v) - \pi(u), where π\pi estimates distance to the destination: if the heuristic is consistent, i.e. w(u,v)+π(v)≥π(u)w(u,v) + \pi(v) \ge \pi(u), this is the same feasibility condition as (1), with h=−πh = -\pi and nonnegative new weights. Dijkstra with those weights explores vertices toward the destination first.

Lab 1: shortest paths from scratch on CSR

The graph uses CSR (compact adjacency lists): arrays indptr, head and w, such that edges of uu occupy positions indptr[u] through indptr[u+1]-1. Everything below uses that structure without graph libraries. The first cell contains DAG paths, indexed heap, both Dijkstra versions, Dial, 0–1 BFS and bidirectional search.

[ ]CSR, DAG paths, Dijkstra (indexed and lazy), Dial, 0–1 BFS and bidirectional searchBrowser
import heapq, random
from collections import deque

INF = float("inf")

class CSR:
    """Grafo dirigido en formato CSR: las aristas que salen de u son las posiciones indptr[u] .. indptr[u+1]-1."""
    def __init__(self, n, aristas):
        aristas = sorted(aristas, key=lambda e: e[0])          # ordenación estable: respeta el orden de inserción por vértice
        self.n, self.m = n, len(aristas)
        self.indptr = [0] * (n + 1)
        for u, _, _ in aristas:
            self.indptr[u + 1] += 1
        for u in range(n):
            self.indptr[u + 1] += self.indptr[u]
        self.head = [v for _, v, _ in aristas]
        self.w = [w for _, _, w in aristas]

    def salen(self, u):
        return range(self.indptr[u], self.indptr[u + 1])

    def con_pesos(self, w):
        h = CSR.__new__(CSR)
        h.n, h.m, h.indptr, h.head, h.w = self.n, self.m, self.indptr, self.head, w
        return h

def camino(pred, v):
    """Reconstruye el camino hasta v siguiendo los predecesores."""
    p = [v]
    while pred[p[-1]] != -1:
        p.append(pred[p[-1]])
    return p[::-1]

# ---------- caminos en un DAG: relajar en orden topológico ----------
def orden_topologico(g):
    grado = [0] * g.n
    for v in g.head:
        grado[v] += 1
    cola = [u for u in range(g.n) if grado[u] == 0]
    for u in cola:                                  # la lista crece mientras se recorre: es la cola de Kahn
        for e in g.salen(u):
            grado[g.head[e]] -= 1
            if grado[g.head[e]] == 0:
                cola.append(g.head[e])
    if len(cola) < g.n:
        raise ValueError("el grafo tiene un ciclo")
    return cola

def caminos_dag(g, s, maximizar=False):
    """Camino mínimo (o máximo, el camino crítico) desde s en O(V + E), con pesos de cualquier signo."""
    signo = -1 if maximizar else 1
    d, pred = [INF] * g.n, [-1] * g.n
    d[s] = 0
    for u in orden_topologico(g):
        if d[u] == INF:
            continue
        for e in g.salen(u):
            v, nd = g.head[e], d[u] + signo * g.w[e]
            if nd < d[v]:
                d[v], pred[v] = nd, u
    return [signo * x for x in d], pred

# ---------- montículo indexado: decrease-key en O(log n) ----------
class MonticuloIndexado:
    def __init__(self, n):
        self.heap, self.pos, self.clave = [], [-1] * n, [INF] * n

    def __len__(self):
        return len(self.heap)

    def _sube(self, i):
        h, p, k = self.heap, self.pos, self.clave
        v = h[i]
        while i > 0 and k[h[(i - 1) // 2]] > k[v]:
            h[i] = h[(i - 1) // 2]
            p[h[i]] = i
            i = (i - 1) // 2
        h[i], p[v] = v, i

    def _hunde(self, i):
        h, p, k = self.heap, self.pos, self.clave
        v, n = h[i], len(h)
        while 2 * i + 1 < n:
            c = 2 * i + 1
            if c + 1 < n and k[h[c + 1]] < k[h[c]]:
                c += 1
            if k[h[c]] >= k[v]:
                break
            h[i] = h[c]
            p[h[i]] = i
            i = c
        h[i], p[v] = v, i

    def inserta_o_baja(self, v, clave):
        self.clave[v] = clave
        if self.pos[v] == -1:
            self.heap.append(v)
            self.pos[v] = len(self.heap) - 1
        self._sube(self.pos[v])

    def extrae_min(self):
        h = self.heap
        v, ultimo = h[0], h.pop()
        self.pos[v] = -1
        if h:
            h[0] = ultimo
            self.pos[ultimo] = 0
            self._hunde(0)
        return v

def dijkstra_indexado(g, s):
    d, pred = [INF] * g.n, [-1] * g.n
    d[s] = 0
    Q = MonticuloIndexado(g.n)
    Q.inserta_o_baja(s, 0)
    extracciones = mejoras = 0
    while len(Q):
        u = Q.extrae_min()
        extracciones += 1
        for e in g.salen(u):
            v, nd = g.head[e], d[u] + g.w[e]
            if nd < d[v]:
                d[v], pred[v] = nd, u
                Q.inserta_o_baja(v, nd)
                mejoras += 1
    return d, pred, extracciones, mejoras

def dijkstra_perezoso(g, s, destino=None):
    """Inserción perezosa: nunca se baja una clave, se inserta una entrada nueva y las viejas se descartan al salir."""
    d, pred = [INF] * g.n, [-1] * g.n
    d[s] = 0
    H = [(0, s)]
    extracciones = obsoletas = 0
    while H:
        du, u = heapq.heappop(H)
        if du > d[u]:                              # entrada obsoleta
            obsoletas += 1
            continue
        extracciones += 1
        if u == destino:                           # parada anticipada: d[destino] ya es definitiva
            break
        for e in g.salen(u):
            v, nd = g.head[e], du + g.w[e]
            if nd < d[v]:
                d[v], pred[v] = nd, u
                heapq.heappush(H, (nd, v))
    return d, pred, extracciones, obsoletas

# ---------- BFS 0-1: pesos en {0, 1} con una cola doble ----------
def bfs01(g, s):
    d, hecho = [INF] * g.n, [False] * g.n
    d[s] = 0
    Q = deque([s])
    while Q:
        u = Q.popleft()
        if hecho[u]:
            continue
        hecho[u] = True
        for e in g.salen(u):
            v, nd = g.head[e], d[u] + g.w[e]
            if nd < d[v]:
                d[v] = nd
                Q.appendleft(v) if g.w[e] == 0 else Q.append(v)
    return d

# ---------- Dial: pesos enteros en 0..C con C + 1 cubetas circulares, O(E + V·C) ----------
def dial(g, s, C):
    d = [INF] * g.n
    d[s] = 0
    cubetas = [[] for _ in range(C + 1)]
    cubetas[0].append(s)
    pendientes, k = 1, 0                            # k es la distancia que se está vaciando
    while pendientes:
        cubeta = cubetas[k % (C + 1)]
        while cubeta:
            u = cubeta.pop()
            pendientes -= 1
            if d[u] != k:                           # entrada obsoleta: u ya se encontró a menor distancia
                continue
            for e in g.salen(u):
                v, nd = g.head[e], k + g.w[e]
                if nd < d[v]:
                    d[v] = nd
                    cubetas[nd % (C + 1)].append(v)
                    pendientes += 1
        k += 1
    return d

# ---------- Dijkstra bidireccional: dos búsquedas que se encuentran a medio camino ----------
def invertido(g):
    return CSR(g.n, [(g.head[e], u, g.w[e]) for u in range(g.n) for e in g.salen(u)])

def bidireccional(g, gr, s, t):
    """Distancia s→t y número de vértices fijados. gr es el grafo con las aristas invertidas."""
    if s == t:
        return 0, 0
    D, H, G = [[INF] * g.n, [INF] * g.n], [[(0, s)], [(0, t)]], (g, gr)
    D[0][s] = D[1][t] = 0
    mu, fijados = INF, 0                            # mu: el mejor camino s→t visto hasta ahora
    while H[0] and H[1] and H[0][0][0] + H[1][0][0] < mu:
        i = 0 if H[0][0][0] <= H[1][0][0] else 1    # se expande el lado con la clave menor
        du, u = heapq.heappop(H[i])
        if du > D[i][u]:
            continue
        fijados += 1
        for e in G[i].salen(u):
            v, nd = G[i].head[e], du + G[i].w[e]
            mu = min(mu, nd + D[1 - i][v])          # camino que une las dos búsquedas por la arista (u, v)
            if nd < D[i][v]:
                D[i][v] = nd
                heapq.heappush(H[i], (nd, v))
    return mu, fijados

# ---------- una prueba rápida con el grafo del interactivo ----------
nombres = "sabcdt"
E = [(0, 1, 4), (0, 2, 2), (2, 1, 1), (1, 3, 3), (2, 4, 7), (3, 4, 2), (3, 5, 6), (4, 5, 1)]
g = CSR(6, E)
d, pred, ext, mej = dijkstra_indexado(g, 0)
print("distancias desde s:", dict(zip(nombres, d)))
print("camino a t:", "→".join(nombres[v] for v in camino(pred, 5)), "| extracciones", ext, "| relajaciones que mejoran", mej)
dp, _, ext2, obs = dijkstra_perezoso(g, 0)
print("perezoso: mismas distancias:", dp == d, "| extracciones útiles", ext2, "| entradas obsoletas", obs)

# camino crítico de un proyecto (DAG con duraciones en las aristas)
tareas = ["inicio", "diseño", "backend", "frontend", "pruebas", "entrega"]
dur = [(0, 1, 3), (1, 2, 5), (1, 3, 4), (2, 4, 6), (3, 4, 3), (4, 5, 2)]
gp = CSR(6, dur)
lmax, pr = caminos_dag(gp, 0, maximizar=True)
print("camino crítico:", " → ".join(tareas[v] for v in camino(pr, 5)), "| duración total", lmax[5])

Output confirms the interactive example: distances 0,3,2,6,8,90, 3, 2, 6, 8, 9 and path s→b→a→c→d→ts \to b \to a \to c \to d \to t. All 88 edges improve an estimate (each vertex is reached for the first time or via a better path), and the lazy version leaves 33 stale entries, those of aa with 44, dd with 99 and tt with 1212. The project’s critical path is design, backend and testing, lasting 1616, and frontend tasks have slack.

The second cell includes Bellman–Ford with cycle extraction, SPFA, vectorized Floyd–Warshall (and pure-loop version for comparison), and Johnson. Try SPFA’s worst case.

[ ]Bellman–Ford with negative cycles, SPFA, vectorized Floyd–Warshall and JohnsonBrowser
import numpy as np

# ---------- Bellman-Ford con extracción del ciclo negativo ----------
def bellman_ford(g, s):
    """Devuelve (d, pred, ciclo, rondas). ciclo es None si no hay ciclo negativo alcanzable desde s."""
    d, pred = [INF] * g.n, [-1] * g.n
    d[s] = 0
    for ronda in range(1, g.n + 1):
        ultimo = -1
        for u in range(g.n):
            if d[u] == INF:
                continue
            for e in g.salen(u):
                v, nd = g.head[e], d[u] + g.w[e]
                if nd < d[v]:
                    d[v], pred[v], ultimo = nd, u, v
        if ultimo < 0:                              # una ronda sin cambios: punto fijo
            return d, pred, None, ronda
    y = ultimo                                      # la ronda V todavía cambió algo: hay un ciclo negativo
    for _ in range(g.n):                            # tras V pasos hacia atrás seguro estamos dentro del ciclo
        y = pred[y]
    ciclo, z = [y], pred[y]
    while z != y:
        ciclo.append(z)
        z = pred[z]
    return d, pred, ciclo[::-1], g.n

def peso_ciclo(g, ciclo):
    tot = 0
    for i, u in enumerate(ciclo):
        v = ciclo[(i + 1) % len(ciclo)]
        tot += min(g.w[e] for e in g.salen(u) if g.head[e] == v)
    return tot

# ---------- SPFA: Bellman-Ford con una cola de vértices cuya distancia ha cambiado ----------
def spfa(g, s):
    d = [INF] * g.n
    d[s] = 0
    Q, en_cola, extracciones, examinadas = deque([s]), [False] * g.n, 0, 0
    en_cola[s] = True
    while Q:
        u = Q.popleft()
        en_cola[u] = False
        extracciones += 1
        for e in g.salen(u):
            examinadas += 1
            v, nd = g.head[e], d[u] + g.w[e]
            if nd < d[v]:
                d[v] = nd
                if not en_cola[v]:
                    en_cola[v] = True
                    Q.append(v)
    return d, extracciones, examinadas

# ---------- Floyd-Warshall: la fila y la columna k se combinan de golpe con NumPy ----------
def matriz_pesos(g):
    W = np.full((g.n, g.n), np.inf)
    np.fill_diagonal(W, 0.0)
    for u in range(g.n):
        for e in g.salen(u):
            W[u, g.head[e]] = min(W[u, g.head[e]], g.w[e])
    return W

def floyd_warshall(W):
    D = W.copy()
    for k in range(len(D)):
        np.minimum(D, D[:, k:k + 1] + D[k:k + 1, :], out=D)      # D[i,j] = min(D[i,j], D[i,k] + D[k,j]) para todos i, j
    return D

def floyd_warshall_python(W):
    n, D = len(W), [list(map(float, fila)) for fila in W]
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if D[i][k] + D[k][j] < D[i][j]:
                    D[i][j] = D[i][k] + D[k][j]
    return np.array(D)

# ---------- Johnson: potenciales con Bellman-Ford y Dijkstra desde cada vértice ----------
def johnson(g):
    """Matriz de distancias con pesos negativos permitidos. Lanza ValueError si hay un ciclo negativo."""
    n = g.n
    aumentado = CSR(n + 1, [(u, g.head[e], g.w[e]) for u in range(n) for e in g.salen(u)] + [(n, v, 0) for v in range(n)])
    h, _, ciclo, _ = bellman_ford(aumentado, n)         # origen virtual n con aristas de peso 0 a todos
    if ciclo is not None:
        raise ValueError("ciclo negativo")
    h = h[:n]
    wp = [g.w[e] + h[u] - h[g.head[e]] for u in range(n) for e in g.salen(u)]
    assert min(wp, default=0) >= 0                     # los pesos nuevos no son negativos
    gp = g.con_pesos(wp)
    D = np.empty((n, n))
    for u in range(n):
        du = dijkstra_perezoso(gp, u)[0]
        D[u] = [du[v] - h[u] + h[v] if du[v] < INF else np.inf for v in range(n)]
    return D

# ---------- el grafo del interactivo de todos los pares: pesos negativos y sin ciclos negativos ----------
nombres = "abcde"
aristas = [(0, 1, 4), (0, 2, 7), (0, 4, -3), (1, 3, 2), (1, 4, 6), (2, 1, 3), (3, 0, 1), (3, 2, -4), (4, 3, 5)]
g = CSR(5, aristas)
d, pred, ciclo, rondas = bellman_ford(g, 0)
print("Bellman-Ford desde a:", dict(zip(nombres, d)), "| rondas hasta el punto fijo:", rondas, "| ciclo:", ciclo)
D = floyd_warshall(matriz_pesos(g))
print("Floyd-Warshall, fila de a:", D[0], "| coincide con BF:", list(D[0]) == d)
print("Johnson coincide con Floyd-Warshall:", np.array_equal(johnson(g), D))

# el mismo grafo con una arista que crea un ciclo negativo (d→a pasa de 1 a −6: a→e→d→a suma −3 + 5 − 6 = −4)
malo = CSR(5, [(u, v, -6 if (u, v) == (3, 0) else w) for u, v, w in aristas])
d, pred, ciclo, rondas = bellman_ford(malo, 0)
print("con la arista d→a = −6:", "ciclo", [nombres[v] for v in ciclo], "de peso", peso_ciclo(malo, ciclo), "| rondas", rondas)
print("Floyd-Warshall lo ve en la diagonal:", np.diag(floyd_warshall(matriz_pesos(malo))).min() < 0)
try:
    johnson(malo)
except ValueError as err:
    print("Johnson lanza:", err)

# ---------- el peor caso de SPFA: un DAG completo con las aristas en el orden equivocado ----------
def dag_adversario(n):
    A = []
    for i in range(n):
        for j in range(n - 1, i, -1):                  # aristas de i en orden descendente de destino
            A.append((i, j, 0 if i == 0 else i - n))   # los pesos bajan al retroceder: cada vértice mejora a todos los siguientes
    return CSR(n, A)

for n in (20, 40, 80):
    ga = dag_adversario(n)
    _, ext, exa = spfa(ga, 0)
    print(f"n = {n:3d}: SPFA extrae {ext:5d} vértices (n(n-1)/2 + 1 = {n*(n-1)//2 + 1}) y examina {exa:6d} aristas (n³/6 = {n**3 // 6}); "
          f"el orden topológico relaja cada arista una vez: {ga.m} aristas")
    assert spfa(ga, 0)[0] == caminos_dag(ga, 0)[0]

Bellman–Ford from aa reaches the fixed point in 3 changing rounds (the fourth changes nothing, confirming it) and distances are 0,1,−2,2,−30, 1, -2, 2, -3, the same as Floyd–Warshall row aa. With d→ad \to a in −6-6, cycle a→e→d→aa \to e \to d \to a of weight −3+5−6=−4-3 + 5 - 6 = -4 appears: Bellman–Ford extracts it, Floyd–Warshall’s diagonal exposes it, and Johnson refuses to continue. In the adversarial DAG, SPFA extracts exactly (n2)+1\binom{n}{2} + 1 vertices: 191,781,3161191, 781, 3161 for n=20,40,80n = 20, 40, 80, and examines 11591159, 99199919 and 82 23982\,239 edges, near n3/6n^3/6 with a ratio approaching 11 as nn grows: cubic growth, Θ(VE)\Theta(VE). On the same edges topological relaxation performs (n2)\binom{n}{2} relaxations, one per edge.

The third cell builds confidence: compare everything with SciPy and NetworkX on random graphs, count Dijkstra key decreases and measure Floyd–Warshall vectorization. For negative-weight graphs without negative cycles it uses Johnson reweighting backward: w(u,v)=c+p(u)−p(v)w(u,v) = c + p(u) - p(v) with c≥0c \ge 0.

[ ]Checking with SciPy and NetworkX, Dial, bidirectional search, key decreases and vectorizationBrowser
import time
import numpy as np
import networkx as nx
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path, dijkstra as sp_dijkstra
from scipy.spatial import cKDTree

rng = random.Random(11)

def grafo_aleatorio(n, m, peso):
    vistas, A = set(), []
    while len(A) < m:
        u, v = rng.randrange(n), rng.randrange(n)
        if u != v and (u, v) not in vistas:
            vistas.add((u, v))
            A.append((u, v, peso(u, v)))
    return A

def a_scipy(n, A):
    u, v, w = zip(*A)
    return csr_matrix((w, (u, v)), shape=(n, n))

# 1. Pesos no negativos: Dijkstra (las dos versiones) frente a SciPy y NetworkX
fallos = 0
for _ in range(20):
    n = rng.randint(30, 80)
    A = grafo_aleatorio(n, 4 * n, lambda u, v: rng.randint(1, 20))
    g, s = CSR(n, A), rng.randrange(n)
    ref = sp_dijkstra(a_scipy(n, A), indices=s)
    G = nx.DiGraph()
    G.add_weighted_edges_from(A)
    nxd = nx.single_source_dijkstra_path_length(G, s) if s in G else {s: 0}
    ref_nx = [nxd.get(v, INF) for v in range(n)]
    for d in (dijkstra_indexado(g, s)[0], dijkstra_perezoso(g, s)[0]):
        fallos += not (np.allclose(d, ref) and np.allclose(d, ref_nx))
print("Dijkstra (indexado y perezoso) frente a SciPy y NetworkX: fallos =", fallos, "de 20 grafos")

# 2. Pesos negativos sin ciclos negativos: w(u,v) = c + p(u) - p(v) con c >= 0 (es la reponderación de Johnson al revés)
fallos = 0
for _ in range(15):
    n = rng.randint(20, 40)
    p = [rng.randint(0, 30) for _ in range(n)]
    A = grafo_aleatorio(n, 3 * n, lambda u, v: rng.randint(0, 8) + p[u] - p[v])
    g = CSR(n, A)
    M = a_scipy(n, A)
    ref_bf = shortest_path(M, method="BF")
    ref_j = shortest_path(M, method="J")
    D_fw = floyd_warshall(matriz_pesos(g))
    D_j = johnson(g)
    d_bf = np.array([bellman_ford(g, s)[0] for s in range(n)])
    d_sp = np.array([spfa(g, s)[0] for s in range(n)])
    fallos += not all(np.allclose(X, ref_bf) for X in (ref_j, D_fw, D_j, d_bf, d_sp))
print("BF, SPFA, Floyd-Warshall y Johnson frente a SciPy con pesos negativos: fallos =", fallos, "de 15 grafos")

# 3. BFS 0-1, Dial y la bidireccional frente a Dijkstra
fallos = 0
for _ in range(30):
    n = rng.randint(20, 100)
    g = CSR(n, grafo_aleatorio(n, 3 * n, lambda u, v: rng.randint(0, 1)))
    fallos += bfs01(g, 0) != dijkstra_perezoso(g, 0)[0]
print("BFS 0-1 frente a Dijkstra: fallos =", fallos, "de 30 grafos")

fallos = 0
for _ in range(30):
    n = rng.randint(20, 100)
    g = CSR(n, grafo_aleatorio(n, 3 * n, lambda u, v: rng.randint(0, 9)))
    fallos += dial(g, 0, 9) != dijkstra_perezoso(g, 0)[0]
print("Dial frente a Dijkstra: fallos =", fallos, "de 30 grafos")

pts = np.random.default_rng(4).random((3000, 2))          # grafo geométrico: cada punto con sus 6 vecinos más próximos
dist, idx = cKDTree(pts).query(pts, 7)
A = {(i, int(j)) for i in range(3000) for j in idx[i, 1:]}
A |= {(j, i) for i, j in A}
g = CSR(3000, [(i, j, int(1000 * np.linalg.norm(pts[i] - pts[j])) + 1) for i, j in A])
gr = invertido(g)
fallos, uni, bi = 0, 0, 0
for _ in range(40):
    s, t = rng.randrange(3000), rng.randrange(3000)
    ref = dijkstra_perezoso(g, s, t)
    mu, fij = bidireccional(g, gr, s, t)
    fallos += mu != ref[0][t]
    uni, bi = uni + ref[2], bi + fij
print(f"bidireccional: fallos = {fallos} de 40 pares | vértices fijados en total: unidireccional {uni}, bidireccional {bi}")

# 4. Cuántas veces se baja una clave en Dijkstra: cuentas, no tiempos (el reloj de Pyodide es grueso)
print("\n   n       m   extracciones  mejoras  obsoletas (perezoso)  mejoras/m")
for n in (500, 2000, 8000):
    g = CSR(n, grafo_aleatorio(n, 5 * n, lambda u, v: rng.randint(1, 1000)))
    _, _, ext, mej = dijkstra_indexado(g, 0)
    _, _, ext2, obs = dijkstra_perezoso(g, 0)
    print(f"{n:6d} {5*n:7d} {ext:12d} {mej:8d} {obs:20d} {mej/g.m:10.2f}")

# 5. Floyd-Warshall vectorizado frente a bucles de Python puro
W = matriz_pesos(CSR(80, grafo_aleatorio(80, 400, lambda u, v: rng.randint(1, 20))))
t0 = time.perf_counter(); A1 = floyd_warshall(W); t1 = time.perf_counter(); A2 = floyd_warshall_python(W); t2 = time.perf_counter()
print(f"\nFloyd-Warshall n = 80: vectorizado {1000*(t1-t0):.1f} ms, bucles puros {1000*(t2-t1):.0f} ms, iguales: {np.array_equal(A1, A2)}")

All algorithms agree with SciPy and NetworkX (zero failures), including negative weights. In the key-decrease table, “improvements” includes first reaching each vertex, yet only about 29 %29\,\% of edges improve, explaining lazy insertion’s good practical performance: it pays log⁡\log per improvement rather than per key decrease. Bidirectional search settles about one third fewer vertices than unidirectional early stopping (48 02248\,022 versus 69 25269\,252 total across 40 pairs) and, as theory says, never fails. Vectorized Floyd–Warshall is already an order of magnitude faster at n=80n = 80 (15–20 times in checker runs on Pyodide; exact factor depends on the machine), with a growing gap at nn because pure loops pay interpreter cost for each of n3n^3 operations.

With libraries

In practice this need not be written from scratch. scipy.sparse.csgraph.shortest_path(M, method=...) accepts 'D' (Dijkstra), 'BF', 'FW' and 'J' (Johnson), with default directed=True and indices= for single source; it raises NegativeCycleError for a negative cycle with BF, FW or J (with 'D' and negative weights it only warns, UserWarning, and correctness is not guaranteed; with a negative cycle the call may not terminate, as checked with SciPy 1.18 and a two-vertex cycle). scipy.sparse.csgraph.dijkstra(..., return_predecessors=True) also returns predecessors. NetworkX exposes single_source_dijkstra, bellman_ford_predecessor_and_distance and johnson. Two cautions: SciPy sparse matrices sum duplicate edges on construction, and weight 00 in a dense matrix means “no edge”, not a zero-weight edge.

Lab 2: geodesic distances and arbitrage

First, Isomap’s central step. A Swiss roll is a flat sheet rolled into a spiral. Its intrinsic geometry is a rectangle with known arc length s(t)s(t), so each estimate’s exact error can be measured. Compare straight-line spatial distance with shortest paths in the kk-neighbor graph for several values of kk.

[ ]Swiss-roll geodesic distances with a k-neighbor graphBrowser
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra as sp_dijkstra, connected_components
from scipy.spatial import cKDTree

# El rollo suizo: una hoja plana (s, y) enrollada en espiral dentro de R^3. Sus distancias intrínsecas se conocen exactamente.
rng = np.random.default_rng(0)
N = 700
t = 1.5 * np.pi * (1 + 2 * rng.random(N))                         # ángulo de la espiral r = t
y = 21 * rng.random(N)
X = np.column_stack([t * np.cos(t), y, t * np.sin(t)])
arco = lambda t: 0.5 * (t * np.sqrt(1 + t * t) + np.arcsinh(t))   # longitud de arco de la espiral desde el centro
s = arco(t)
real = np.hypot(s[:, None] - s[None, :], y[:, None] - y[None, :])  # distancia dentro de la hoja desenrollada (es convexa)
euclid = np.linalg.norm(X[:, None, :] - X[None, :, :], axis=2)     # distancia en línea recta por el espacio

def grafo_knn(X, k):
    """Grafo no dirigido de los k vecinos más próximos, con la distancia euclídea como peso."""
    dist, idx = cKDTree(X).query(X, k + 1)
    filas = np.repeat(np.arange(len(X)), k)
    G = csr_matrix((dist[:, 1:].ravel(), (filas, idx[:, 1:].ravel())), shape=(len(X), len(X)))
    return G.maximum(G.T)                                         # simétrico: vecino de uno o del otro

def error_mediano(D, mascara):
    return np.median(np.abs(D[mascara] - real[mascara]) / real[mascara])

lejos = real > 20                                                   # pares separados en la hoja
print("distancia por línea recta (Euclídea): error relativo mediano en pares lejanos =", round(error_mediano(euclid, lejos), 3))
print("   k   componentes   error mediano (pares lejanos)   error máximo")
for k in (5, 8, 20, 100):
    G = grafo_knn(X, k)
    comp = connected_components(G, directed=False)[0]
    D = sp_dijkstra(G, directed=False)                              # Dijkstra desde cada vértice: el paso central de Isomap
    ok = np.isfinite(D) & lejos
    print(f"{k:4d} {comp:12d} {error_mediano(D, ok):26.3f} {np.max(np.abs(D[ok] - real[ok]) / real[ok]):16.3f}")

Straight-line distance errs by around 52 %52\,\% for distant pairs (it crosses the roll’s gap), while with k=8k = 8 the graph gives median error about 5 %5\,\%: shortest paths follow the sheet. With k=5k = 5 error is larger (near 11 %11\,\%) because the graph has many detours. With large kk, shortcuts appear between turns, edges crossing the gap, so shortest paths become almost straight again: with k=100k = 100 median error is 48 %48\,\%, and already at k=20k = 20 some pairs err by more than 90 %90\,\% and the median jumps to nearly a quarter. One shortcut edge ruins many distances. This is why Isomap is sensitive to kk (covered in its lesson).

Second, arbitrage using this lesson’s own Bellman–Ford implementation (the cell shares lab 1’s namespace).

[ ]Currency arbitrage with our Bellman–Ford, checked against brute forceBrowser
import itertools, math

DIVISAS = ["EUR", "USD", "GBP", "JPY"]
PRECIO = [1.0, 1.08, 0.85, 162.0]            # unidades de cada divisa por 1 EUR: valores inventados para el ejemplo
TASA = [[b / a for b in PRECIO] for a in PRECIO]         # tabla coherente: TASA[i][j] = unidades de j por 1 de i

def detectar_arbitraje(tasa, comision=0.0):
    """Bellman-Ford propio sobre pesos -ln(tasa efectiva). Devuelve (ciclo de divisas, producto de las tasas) o None."""
    n = len(tasa)
    A = [(i, j, -math.log(tasa[i][j] * (1 - comision))) for i in range(n) for j in range(n) if i != j]
    A += [(n, i, 0.0) for i in range(n)]                     # origen virtual: alcanza todas las divisas
    g = CSR(n + 1, A)
    _, _, ciclo, _ = bellman_ford(g, n)
    if ciclo is None:
        return None
    return ciclo, math.exp(-peso_ciclo(g, ciclo))

def mejor_ciclo_bruto(tasa, comision=0.0):
    """Producto máximo sobre todos los ciclos simples (n pequeño)."""
    n, mejor = len(tasa), 1.0
    for r in range(2, n + 1):
        for sub in itertools.permutations(range(n), r):
            p = 1.0
            for a, b in zip(sub, sub[1:] + sub[:1]):
                p *= tasa[a][b] * (1 - comision)
            mejor = max(mejor, p)
    return mejor

c = 0.0005                                                    # comisión del 0.05 % por operación
print("tabla coherente:", detectar_arbitraje(TASA, c))
rotas = [[fila[:] for fila in TASA] for _ in range(2)]
rotas[0][0][3] *= 1.006                                       # EUR→JPY, 0.6 % mejor de lo debido
rotas[1][1][2] *= 1.003                                       # USD→GBP, 0.3 % mejor de lo debido
for k, T in enumerate(rotas):
    r = detectar_arbitraje(T, c)
    print(f"tabla {k + 1}:", [DIVISAS[v] for v in r[0]] if r else None, "producto de tasas", round(r[1], 5) if r else None, "| mejor ciclo por fuerza bruta", round(mejor_ciclo_bruto(T, c), 5))

# Contraste con la fuerza bruta en tablas con ruido: Bellman-Ford debe encontrar un ciclo exactamente cuando existe uno rentable
rnd = random.Random(2)
desacuerdos = con_arbitraje = 0
for _ in range(300):
    T = [[TASA[i][j] * math.exp(rnd.gauss(0, 0.0004)) if i != j else 1.0 for j in range(4)] for i in range(4)]
    r, bruto = detectar_arbitraje(T, c), mejor_ciclo_bruto(T, c)
    con_arbitraje += bruto > 1
    desacuerdos += (r is not None) != (bruto > 1)
    if r is not None:
        assert r[1] > 1
print("tablas con ruido: con arbitraje", con_arbitraje, "de 300 | desacuerdos con la fuerza bruta:", desacuerdos)

With a consistent table and 0.05 %0.05\,\% commission there is no arbitrage: each cycle loses commissions on its edges. With 0.6 %0.6\,\% bias in EUR→JPY, the two-step cycle EUR→JPY→EUR gives product 1.004991.00499, exactly 1.006×(1−0.0005)21.006 \times (1 - 0.0005)^2, the best possible cycle by brute force. Across 300 noisy tables (71 with arbitrage), Bellman–Ford and brute force never disagree on whether any profitable cycle exists (the returned cycle need not be best, just have product exceeding 11, what assert checks).

Common mistakes

The frontier: the sorting barrier

Dijkstra dates to 1959 and its O(E+Vlog⁡V)\bigO(E + V \log V) Fibonacci-heap cost was long considered unbeatable in the comparison model with real weights. Two recent works change the picture and should be read together because they say different things.

Breaking the barrier. Duan, Mao, Mao, Shu and Yin (2025) give a deterministic O(mlog⁡2/3n)\bigO(m \log^{2/3} n) algorithm for single-source shortest paths in directed graphs with nonnegative real weights, in the comparisons-and-additions model. It first improves Dijkstra’s O(m+nlog⁡n)\bigO(m + n \log n) for sparse directed graphs (for undirected graphs, Duan, Mao, Shu and Yin had already given a randomized O(mlog⁡nlog⁡log⁡n)\bigO(m \sqrt{\log n \log\log n}) algorithm in 2023), proving Dijkstra is not optimal for computing distances. Carefully summarized: Dijkstra pays log⁡V\log V per vertex by settling vertices in sorted distance order. The new algorithm avoids fully sorting the frontier, combining Dijkstra-style distance expansion with Bellman–Ford-like steps on groups of vertices so the maintained ordered frontier shrinks recursively. Details are in the paper; the message is computing distances does not require sorting vertices by distance. The bound has been improved: in February 2026 Duan, Mao, Shu and Yin posted on arXiv (arXiv:2602.07868) a deterministic directed-graph O(mlog⁡n+mnlog⁡nlog⁡log⁡n)\bigO(m \sqrt{\log n} + \sqrt{m n \log n \log\log n}) algorithm based on the same recursion.

Universal optimality of Dijkstra. Haeupler, Hladík, Rozhoň, Tarjan and Tětek (2024) prove an apparently opposite result: Dijkstra with an appropriate heap is universally optimal for sorting vertices by distance from the source. Universal means that, for each graph (its structure, not weights), the algorithm’s worst case over weights takes as many operations as the best possible algorithm up to a constant: a “beyond worst case” guarantee comparing graph by graph, not just the hardest input. The key heap has the working-set property: it retains Fibonacci-heap amortized bounds, but extracting the minimum costs a logarithm of the number of elements inserted after that element and before extraction, rather than heap size, making recently relaxed vertices cheap to extract.

Key idea
The results do not contradict each other because they address different problems. If distance ordering of vertices is required, Dijkstra with a working-set heap is optimal for every graph, and the Ω(Vlog⁡V)\Omega(V \log V) barrier is real in the worst case. If only the distance table is required, algorithms can avoid that sorting cost and beat it on sparse graphs.

A reading caveat: Duan et al.’s result is theoretical (constants and implementation complexity do not currently make it competitive with good Dijkstra) in the comparisons-and-additions model with nonnegative real weights; it is not a recipe for replacing Dijkstra on a routing server. It changes what is known about a heavily studied algorithmic problem and shows that a sorting-model lower bound can stop being relevant when the actual problem does not require sorting.

Exercises

ProofDijkstra by contradiction
Prove: If w≥0w \ge 0, when Dijkstra extracts vertex uu from the heap, its tentative distance is the true distance: d[u]=δ(s,u)d[u] = \delta(s, u).
0
This time do not use the lesson's invariant: prove by contradiction. Let SS be settled vertices and uu the first settled vertex with d[u]≠δ(s,u)d[u] \ne \delta(s, u). Assume u≠su \ne s and uu is reachable, and let PP be a shortest path from ss to uu.

Step 1 of 5. When uu is extracted, what do we know about already-settled vertices?

ProofJohnson reweighting
Prove: Let hh be a feasible potential (h(v)≤h(u)+w(u,v)h(v) \le h(u) + w(u,v) for every edge) and w′(u,v)=w(u,v)+h(u)−h(v)w'(u,v) = w(u,v) + h(u) - h(v). Then w′≥0w' \ge 0 and shortest paths from ss to tt are the same under ww and w′w'.
0
Prove nonnegativity and preservation of shortest paths. Consider any path p=(v0,…,vk)p = (v_0, \dots, v_k).

Step 1 of 4. How do you prove w′(u,v)≥0w'(u,v) \ge 0?

Code0–1 BFS with a deque
Implement bfs01(n, adj, s). The graph has n vertices numbered 0 through n-1; adj[u] is a list of pairs (v, w) with w equal to 0 or 1. Return distances from s (float('inf') for unreachable vertices). Use a deque (collections.deque) instead of a heap: the test prohibits heapq.heappush and heapq.heappop and checks each vertex is expanded at most once (linear cost).
from collections import deque

def bfs01(n, adj, s):
  # distancias desde s con pesos 0 o 1, con una cola doble
  pass
Shift+Enter to run
NumericBellman–Ford by hand
A five-vertex graph s,a,b,c,ts, a, b, c, t has edges s→a (5)s \to a\ (5), s→b (9)s \to b\ (9), a→b (−3)a \to b\ (-3), a→c (6)a \to c\ (6), b→c (−1)b \to c\ (-1), b→t (4)b \to t\ (4) and c→t (2)c \to t\ (2). Run Bellman–Ford from ss with synchronous rounds (each round relaxes every edge reading only previous-round distances). After round 2, what is the sum of finite distances d(s)+d(a)+d(b)+d(c)+d(t)d(s) + d(a) + d(b) + d(c) + d(t)?
NumericJohnson potentials
The all-pairs interactive graph has vertices a,b,c,d,ea, b, c, d, e and edges a→b (4)a \to b\ (4), a→c (7)a \to c\ (7), a→e (−3)a \to e\ (-3), b→d (2)b \to d\ (2), b→e (6)b \to e\ (6), c→b (3)c \to b\ (3), d→a (1)d \to a\ (1), d→c (−4)d \to c\ (-4) and e→d (5)e \to d\ (5). Add vertex qq with 00-weight edges to all and compute h(v)=δ(q,v)h(v) = \delta(q, v). What is h(a)+h(b)+h(c)+h(d)+h(e)h(a) + h(b) + h(c) + h(d) + h(e)?
QuizDijkstra and negative weights
Choose all true statements.

More than one answer may be correct.

QuizChoose the algorithm
Choose the correct algorithm assignment. (A) Single source in a sparse graph with nonnegative weights. (B) Single source in a DAG with negative weights. (C) All pairs in a dense 500-vertex graph with arbitrary weights and no negative cycles. (D) All pairs, by rows or queries, in a sparse graph with 10510^5 vertices and nonnegative weights.

Summary

Key idea
All shortest-path algorithms relax edges, d[v]←min⁡(d[v],d[u]+w(u,v))d[v] \leftarrow \min(d[v], d[u] + w(u,v)), differing only in order. Relaxation never goes below true distance, and it suffices for every shortest path to have its edges relaxed in order: topological order (DAG), increasing distance (Dijkstra, with w≥0w \ge 0), V−1V - 1 full rounds (Bellman–Ford), or increasing intermediate vertices (Floyd–Warshall).
  • Relaxation. Upper bound, convergence and path relaxation. A predecessor-subgraph cycle is negative; without negative cycles, the predecessor subgraph is a shortest-path tree.
  • DAG. Topological order and one pass, O(V+E)\bigO(V + E), for weights of any sign. Replacing min⁡\min by max⁡\max gives the critical path.
  • Dijkstra. Invariants (I1) and (I2); the only line using w≥0w \ge 0. Binary heap O((V+E)log⁡V)\bigO((V+E)\log V) (indexed or lazy), Fibonacci O(E+Vlog⁡V)\bigO(E + V \log V). One negative weight causes silent failure; reopening fixes correctness but loses the bound.
  • Variants. Dial buckets (O(E+VC)\bigO(E + VC)), 0–1 BFS with deque (O(V+E)\bigO(V + E)), bidirectional search with criterion cimaf+cimab≥μ\text{cima}_f + \text{cima}_b \ge \mu.
  • Bellman–Ford. After kk rounds, paths of at most kk edges; a changing round VV detects a reachable negative cycle, extracted via predecessors. SPFA has no better guarantee than O(VE)\bigO(VE). Currency arbitrage is a negative cycle with weights −ln⁡r-\ln r.
  • All pairs. Floyd–Warshall Θ(V3)\Theta(V^3), vectorizable with NumPy; Johnson reweights with Bellman–Ford hh then runs VV Dijkstras. Dense: Floyd–Warshall; sparse: Johnson; without negative weights: repeated Dijkstra.
  • Frontier. A deterministic O(mlog⁡2/3n)\bigO(m \log^{2/3} n) algorithm beats Dijkstra on sparse graphs without sorting vertices, while Dijkstra with a working-set heap is universally optimal when distance ordering is required.