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 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 . 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 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 be a directed graph with weight function , with and (in costs we conventionally write and for and ). The weight of a path is .
Distinguish the two infinities: means “no path” and means “no best path”. If no negative cycle is reachable from , the infimum is attained by a simple path (at most edges): removing a nonnegative-weight cycle cannot worsen a walk. Unless stated otherwise, that is the setting.
Proof
If a lower-weight path from to existed, substituting it in would give a walk from to of lower weight than , contradicting minimality of .
∎This gives the triangle inequality: for every edge , , since a shortest path to followed by the edge is a walk to . 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 (the empty path weighs , so ) and the rest equal . If relaxation sets , then by induction and triangle inequality. Since only decreases and never below , a value equal to remains fixed.
(2) After relaxation, , where the final equality is optimal substructure (the path to prefixes a shortest path to ). By (1), .
(3) Induct on : after relaxing , . For , . The step uses (2) and the fact that by (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 . The predecessor subgraph has edges for with defined. A simple invariant governs it: if , then at all times. When is set there is equality, and afterward can only decrease while does not change as long as remains .
Proof
Let be a cycle with . All its vertices have finite . Consider when its last edge was set, say : just before, relaxation improved, so (strict inequality), while for the other already-present cycle edges holds. Summing the inequalities cancels the terms (each cycle vertex appears once on each side), leaving .
∎Thus if no reachable negative cycles exist, the predecessor subgraph is acyclic; since is the only vertex with finite and no predecessor (every other obtained its value by relaxation), every predecessor chain ends at and the subgraph is a tree rooted at . When everywhere it is a shortest-path tree rooted at : every tree path from is shortest. Thus algorithms return and together: is the distance table and 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 and every shortest path is simple. In topological order, precedes , which precedes , and so on. Processing relaxes , and these relaxations occur in order . By path relaxation, . If is unreachable, never changes and equals .
∎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 to 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 is dynamic programming whose subproblem graph is the graph itself, evaluable in topological order precisely because it is acyclic. The same scheme with 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.
What you should see with positive weights: each vertex is extracted once in increasing distance order ( with distances ), and frontier estimates fall as the frontier advances (for example falls from to when is extracted and relaxed). The first proof step describes the state as an invariant.
Proof
Initially and both conditions hold: and the rest is . The first iteration extracts (the only vertex with finite ), with (with there are no negative cycles). Now assume both conditions hold with , and is extracted with finite minimum among unsettled vertices. Prove .
Let be a shortest path from to (it exists: finite means is reachable, and with there are no negative cycles). By the upper bound, . Let be the first vertex of outside (it exists since ), and its predecessor in , in (the first vertex of is ). By (I1), , and by (I2) , with the final equality from optimal substructure. Since , . Now use nonnegative weights: the prefix of through weighs no more than , so . Combining everything, and with from minimum ,
so and (I1) remains true after adding to . For (I2), relaxing ‘s edges changes each to , exactly the (I2) minimum with instead of .
Each iteration settles a vertex, so the algorithm terminates. On termination vertices outside have , and by (I2) no edge leaves for them: they are unreachable from , and .
∎The proof reveals what fails with negative weights: “the prefix weighs no more than ” is the only line using . With a negative weight, a path through an unsettled vertex can end up shorter. The interactive’s minimal counterexample: with weight , with , with and with . Dijkstra extracts with and leaves ; then extracts , relaxes and falls to , but was settled, does not return to the heap, and remains when . There is no error signal: the algorithm terminates and returns a normal-looking table.
Which heap and at what cost
The algorithm performs extractions and examines every edge once; each examination may lower an estimate. Priority-queue structure determines cost:
- Indexed binary heap (decrease-key in ): extractions and at most key decreases, total. An index of each vertex’s position is needed.
- Lazy insertion: do not decrease keys; each improvement inserts a new entry, discarding old entries upon extraction ( greater than ). The heap has at most entries and costs . 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 ( edges) to up to .
- Fibonacci heap (decrease-key in amortized , extract-min in amortized ): . This is the classical theoretical bound, though constants make it rarely competitive in practice. An -ary heap of gives (Johnson, 1977), already linear for dense graphs.
- Small-weight graphs (next section): buckets or deque.
The comparison sorting lower bound explains why appears throughout: Dijkstra extracts vertices in increasing distance order, sorting them by distance, which costs in the comparison model. This is the “sorting barrier” of the final section.
Two practical observations. If only destination matters, stop when is extracted: its distance is final by (I1), avoiding the rest of the graph. Dijkstra from 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 because each decreased vertex is reexpanded; summing inequalities along a shortest path gives and, with the upper bound, . But the greedy guarantee disappears: no longer “one extraction per vertex”, extractions can exceed 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.
Small-weight variants and bidirectional search
The first two variants exploit small integer weights to avoid a heap.
Dial (buckets). For integer weights in , tentative estimates always lie in window , where is the distance being settled. Store vertices in circular buckets; bucket contains vertices with , and traverse emptying each bucket. Cost is : at most empty buckets are visited (maximum distance at most ) and relaxations performed.
0–1 BFS. For weights in , replace the priority queue with a deque: an edge of weight inserts the neighbor at the front, weight at the back. This works because queue keys remain ordered and in , where is the front vertex’s distance: on extracting a vertex with , front insertions have key and back insertions , preserving order. This is Dijkstra with a structure extracting the minimum in , giving . It illustrates avoiding the sorting barrier when keys have a small range. You implement it in an exercise.
Bidirectional search. For query run two Dijkstras, one from on and one from on the reverse graph, alternating by smallest top key. Maintain , the best path seen, updated at each examined edge using . The correct stopping condition is not “the frontiers meet”, but .
Proof
Since is the weight of a real path, . Suppose a path from to has weight . By Dijkstra correctness, every vertex with is settled forward with , and every vertex with is settled backward with . Traverse and let be the prefix weight through and the suffix weight. Since , there is an edge of with and : if is the first vertex of with , then , and its predecessor satisfies . Then is settled forward with and backward with . Edge is examined when the latter is settled (from in forward search or backward), updating with a value . Then : contradiction. Two edge cases remain, using that and hold from the start: if no vertex of has , all are settled forward, in particular the penultimate , and examining gives ; if the first with is itself (i.e. ), its successor on has , is settled backward, and examining from gives .
∎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 have half the area of one of radius .
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 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 . For only has value . A walk from to with at most edges either has at most (weight at least ), or exactly : its final edge is some and the rest a walk to with edges, weighing at least . Thus the minimum is , 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 edges, and after rounds . One more round changes nothing.
Detecting and extracting negative cycles
Proof
() Without reachable negative cycles, after rounds , and property 1 prevents further decreases. () If round changes nothing, for every edge with reachable . Let be a reachable cycle: all its vertices have finite and summing around it gives . Thus the cycle is not negative.
∎Existence alone is not enough: we want the cycle, obtained from predecessors.
Proof
If ‘s predecessor chain terminated (at a vertex without predecessor, which can only be ), it would be a simple path with and, summing the predecessor invariant along (with because has no predecessor), , where is the minimum weight of a walk from to with at most edges. But by the round invariant after round was already at most , and decreased in round , so : contradiction. The chain does not terminate, and since there are vertices, after 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 , explaining its reputation. But its worst case remains , and simple inputs trigger it. The lab shows a complete DAG of vertices with edges listed in the wrong order: SPFA extracts vertices and examines on the order of edges, i.e. with , 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 from to (units of per unit of ). Trading around cycle multiplies capital by ; arbitrage occurs when the product exceeds . Taking negative logarithms, , a product above becomes a weight sum below : a negative cycle. Technical detail: no source necessarily reaches every cycle, so add a virtual source with edges of weight to every currency, as in Johnson.
Notice the figure’s model–reality relationship. With consistent rates and no commission, each cycle has exactly product and weight sum : no negative cycle exists, and Bellman–Ford stops in round or shortly after. Bias 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 and assume no loops (a negative one is already a negative cycle; a nonnegative one is useless). Let be the best path weight from to whose intermediate vertices belong to . Floyd–Warshall dynamic programming uses recurrence
Proof
Induct on . A simple shortest path from to with intermediates in either avoids (weight ) or visits exactly once and splits into paths and , both with intermediates in 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 from to with intermediates in , holds. If avoids , use the hypothesis for and ; if it visits , split it into two simple pieces with intermediates . Now let be a negative simple cycle and its greatest-index vertex. Its other vertices are below , and is a “path” from to with intermediates in , so . Conversely every value is the weight of a walk, so is a negative closed cycle.
∎Cost is time and memory ( can be overwritten in place because while , i.e. without negative cycles through , row and column do not change during iteration ; with negative cycles, the in-place version still marks them on the diagonal). The inner loop is useful: iteration is an outer sum of column and row 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 instead of gives fixed-edge-count paths, and squaring times computes all pairs in , worse than Floyd–Warshall but within semiring dynamic programming.
Johnson: change the graph to use Dijkstra
For a sparse graph, Dijkstra runs cost , much less than . Negative weights are the obstacle. Johnson’s idea is to transform them.
Proof
(1) This is feasibility: . (2) Sum along telescopes, leaving . (3) All paths from to change by the same constant , so minimizing and gives the same minimizers. For a cycle and the constant is . Finally reaches every vertex and is finite iff no negative cycles exist (the only cycles are those of , since no edge enters ), and triangle inequality gives feasibility.
∎Johnson’s algorithm is then: Bellman–Ford from (), reweight, Dijkstra from each vertex with , undo the change with . Fibonacci heap cost , binary heap .
Which to choose? In a dense graph, with , Floyd–Warshall costs and Johnson too ( with Fibonacci, with binary heap), so Floyd–Warshall wins on simplicity and vectorization. On sparse graphs Johnson clearly wins ( versus ). If weights are already nonnegative, neither Bellman–Ford nor reweighting is needed: Dijkstra runs. With the result matrix itself does not fit ( entries); request rows or only necessary queries.
Reweighting recurs elsewhere. A* search is Dijkstra on the graph reweighted by , where estimates distance to the destination: if the heuristic is consistent, i.e. , this is the same feasibility condition as (1), with 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 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.
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 and path . All edges improve an estimate (each vertex is reached for the first time or via a better path), and the lazy version leaves stale entries, those of with , with and with . The project’s critical path is design, backend and testing, lasting , 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.
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 reaches the fixed point in 3 changing rounds (the fourth changes nothing, confirming it) and distances are , the same as Floyd–Warshall row . With in , cycle of weight appears: Bellman–Ford extracts it, Floyd–Warshall’s diagonal exposes it, and Johnson refuses to continue. In the adversarial DAG, SPFA extracts exactly vertices: for , and examines , and edges, near with a ratio approaching as grows: cubic growth, . On the same edges topological relaxation performs 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: with .
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 of edges improve, explaining lazy insertion’s good practical performance: it pays per improvement rather than per key decrease. Bidirectional search settles about one third fewer vertices than unidirectional early stopping ( versus total across 40 pairs) and, as theory says, never fails. Vectorized Floyd–Warshall is already an order of magnitude faster at (15–20 times in checker runs on Pyodide; exact factor depends on the machine), with a growing gap at because pure loops pay interpreter cost for each of 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 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 , so each estimate’s exact error can be measured. Compare straight-line spatial distance with shortest paths in the -neighbor graph for several values of .
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 for distant pairs (it crosses the roll’s gap), while with the graph gives median error about : shortest paths follow the sheet. With error is larger (near ) because the graph has many detours. With large , shortcuts appear between turns, edges crossing the gap, so shortest paths become almost straight again: with median error is , and already at some pairs err by more than and the median jumps to nearly a quarter. One shortcut edge ruins many distances. This is why Isomap is sensitive to (covered in its lesson).
Second, arbitrage using this lesson’s own Bellman–Ford implementation (the cell shares lab 1’s namespace).
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 commission there is no arbitrage: each cycle loses commissions on its edges. With bias in EUR→JPY, the two-step cycle EUR→JPY→EUR gives product , exactly , 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 , what assert checks).
Common mistakes
The frontier: the sorting barrier
Dijkstra dates to 1959 and its 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 algorithm for single-source shortest paths in directed graphs with nonnegative real weights, in the comparisons-and-additions model. It first improves Dijkstra’s for sparse directed graphs (for undirected graphs, Duan, Mao, Shu and Yin had already given a randomized algorithm in 2023), proving Dijkstra is not optimal for computing distances. Carefully summarized: Dijkstra pays 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 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.
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
Step 1 of 5. When is extracted, what do we know about already-settled vertices?
Step 1 of 4. How do you prove ?
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
passMore than one answer may be correct.
Summary
- 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, , for weights of any sign. Replacing by gives the critical path.
- Dijkstra. Invariants (I1) and (I2); the only line using . Binary heap (indexed or lazy), Fibonacci . One negative weight causes silent failure; reopening fixes correctness but loses the bound.
- Variants. Dial buckets (), 0–1 BFS with deque (), bidirectional search with criterion .
- Bellman–Ford. After rounds, paths of at most edges; a changing round detects a reachable negative cycle, extracted via predecessors. SPFA has no better guarantee than . Currency arbitrage is a negative cycle with weights .
- All pairs. Floyd–Warshall , vectorizable with NumPy; Johnson reweights with Bellman–Ford then runs Dijkstras. Dense: Floyd–Warshall; sparse: Johnson; without negative weights: repeated Dijkstra.
- Frontier. A deterministic algorithm beats Dijkstra on sparse graphs without sorting vertices, while Dijkstra with a working-set heap is universally optimal when distance ordering is required.