---
title: All-Pairs Shortest Paths (APSP)
url: https://www.emergentmind.com/topics/all-pairs-shortest-paths-apsp
type: topic
---

# All-Pairs Shortest Paths (APSP)

All-pairs shortest paths (APSP) is the problem of computing the shortest-path distance $\delta_G(u,v)$ for every ordered pair of vertices in a weighted directed or undirected graph $G=(V,E)$, where

$$
\delta_G(u,v)=\min_{P:u\leadsto v}\sum_{e\in P}w(e).
$$

A missing edge is assigned weight $\infty$. Depending on the formulation, APSP may also require shortest-path witnesses, shortest-path DAGs, path multiplicities, or queries and updates to a maintained distance structure. APSP is a central problem in combinatorial optimization, graph algorithms, distributed computing, dynamic algorithms, fine-grained complexity, and hardware acceleration. Its unrestricted sequential baseline is $O(n^3)$ through Floyd–Warshall or straightforward repeated single-source shortest paths, while the best general classical bound cited in the literature is $n^3/2^{\Omega(\sqrt{\log n})}$, which is not truly subcubic in the usual $O(n^{3-\varepsilon})$ sense [1410.6220].

## 1. Problem definition, computational structure, and classical baselines

For a graph with $n=|V|$, APSP outputs an $n\times n$ distance matrix. In directed graphs, ordered pairs must be distinguished; in undirected graphs, distances are symmetric, although algorithms may still represent both orientations. The standard model permits arbitrary real weights when negative cycles are excluded. Positive or nonnegative weights are frequently assumed for algorithms based on Dijkstra’s method, while DAG algorithms can accommodate arbitrary real weights because acyclicity precludes negative cycles.

The central algebraic operation is the distance product, or min-plus product,

$$
C[i,j]=\min_k\{A[i,k]+B[k,j]\}.
$$

Repeated min-plus squaring computes the closure of a weighted adjacency matrix. If there are no negative cycles, a shortest simple path uses at most $n-1$ edges, so repeated squaring requires $O(\log n)$ distance products. Floyd–Warshall instead applies the recurrence

$$
D_{ij}^{(k)}
=
\min\left(D_{ij}^{(k-1)},D_{ik}^{(k-1)}+D_{kj}^{(k-1)}\right),
$$

which yields $O(n^3)$ time and $O(n^2)$ space.

For sparse graphs with nonnegative weights, Johnson’s algorithm has running time

$$
O(|V||E|+|V|^2\log |V|),
$$

although dense matrix-based algorithms may have higher computational density in practice. In undirected unweighted graphs, Seidel’s algorithm computes exact APSP in $\widetilde O(n^\omega)$ time, where $\omega$ is the exponent of square matrix multiplication. The distinction between weighted and unweighted graphs is fundamental: exact unweighted undirected APSP admits algebraic subcubic algorithms, whereas exact weighted APSP remains associated with the weighted APSP conjecture, which asserts that no truly subcubic algorithm exists for general weighted instances.

The output size alone imposes an $\Omega(n^2)$ lower bound when all distances are explicitly produced. This lower bound is approached by several approximate algorithms, but exact general weighted APSP remains substantially more expensive.

## 2. Algorithmic paradigms for static APSP

A recurring technique is to separate shortest paths by hop length. For a parameter $\ell$, paths are divided into short paths containing at most $\ell$ vertices or edges and long paths containing at least $\ell$ vertices. Short paths are computed using matrix products or specialized recurrences. Long paths are handled by a hitting set, or blocker set, of size approximately $\widetilde O(n/\ell)$ that intersects every relevant long shortest path.

If $S$ is such a set, then for pairs whose shortest paths are long,

$$
\delta_G(u,v)=\min_{s\in S}\bigl(\delta_G(u,s)+\delta_G(s,v)\bigr).
$$

Quantum algorithms use this framework with Grover search and quantum Dijkstra. A quantum Dijkstra computation costs $\widetilde O(n^{1.5})$ per source, while a direct Grover evaluation of one distance-product entry costs $\widetilde O(\sqrt n)$. Consequently, the unrestricted quantum baseline for APSP is

$$
\widetilde O(n^{2.5}),
$$

obtained by evaluating all $n^2$ entries of a distance product. Structured instances permit improvements below this baseline, but the cited quantum work does not provide a truly sub-$n^{2.5}$ algorithm for unrestricted APSP [1410.6220].

Geometric structure provides one such improvement. In geometrically weighted graphs, edge weights are generated by a constant-size family of piecewise-algebraic functions over points in constant-dimensional space. A geometric partition theorem bounds the number of cells intersected by a relevant algebraic boundary. If $\kappa$ is the corresponding partition parameter, a geometric distance product can be computed in

$$
\widetilde O\left(n^{\frac{5\kappa+\omega}{2\kappa+1}}\right)
$$

time. For node-weighted graphs, $\kappa=1$, giving approximately $\widetilde O(n^{2.458})$ for the product; for Euclidean graphs, $\kappa=3$, giving approximately $\widetilde O(n^{2.482})$.

Applying the product repeatedly to short paths and a hitting-set method to long paths yields geometric APSP in

$$
\widetilde O\left(
n^{\,2.5-\frac{2.5-\omega}{4\kappa+2}}
\right).
$$

The stated special cases are approximately $\widetilde O(n^{2.479})$ for node-weighted graphs and $\widetilde O(n^{2.491})$ for Euclidean graphs. For geometrically weighted graphs with edge weights in $[1,c]$, sparsity of intermediate matrices gives the stronger bound

$$
\widetilde O\left(n^{\frac{5\kappa+\omega}{2\kappa+1}}\right).
$$

Other structured variants exploit a bounded number of outgoing weight values per vertex, or monotonicity constraints. For at most $L$ distinct outgoing weights per vertex, the cited quantum bound is

$$
\widetilde O\left(
\sqrt L\,n^{\,2.5-(2.5-\omega)/6}
\right).
$$

For all-pairs nondecreasing paths, also called earliest-arrival paths, specialized $(\min,\leq)$ products and a modified quantum Dijkstra procedure yield

$$
\widetilde O(n^{2.487}).
$$

These improvements are conditional on structural restrictions; they do not establish a general $O(n^{2.5-\varepsilon})$ quantum algorithm.

## 3. Distributed and parallel APSP

Distributed APSP depends strongly on the communication model. In the Congest model, nodes communicate synchronously over graph edges using $O(\log n)$-bit messages, and complexity is measured in rounds. A deterministic exact weighted algorithm based on bounded-hop shortest-path trees and blocker sets computes APSP in

$$
O\!\left(n^{3/2}\sqrt{\log n}\right)
=
\widetilde O(n^{3/2})
$$

rounds. The construction chooses

$$
h=\sqrt{n\log n},
$$

builds all $h$-hop shortest-path trees, constructs a blocker set of size $O(n\log n/h)$, runs full single-source shortest paths from blocker vertices, and reconstructs every distance using

$$
\delta(u,v)=
\min\left\{
\delta_h(u,v),
\min_{c\in Q}\bigl[\delta_h(u,c)+\delta(c,v)\bigr]
\right\}.
$$

A subsequent deterministic algorithm improves the Congest bound to $\widetilde O(n^{4/3})$ for arbitrary nonnegative real weights in directed and undirected graphs [2005.09588]. It uses $h=n^{1/3}$, a deterministic blocker construction based on approximate hypergraph set cover, and a deterministic frame-based round-robin schedule for propagating source-to-blocker distances. The blocker set has size $\widetilde O(n^{2/3})$, and both the $h$-hop computations and the central propagation step take $\widetilde O(n^{4/3})$ rounds.

For directed unweighted graphs, pipelined source-distance records yield linear-round algorithms. A node orders source-distance pairs by distance and source identifier, and schedules transmissions using distance plus list position. The resulting algorithm computes exact APSP in

$$
\min\{2n,n+O(D)\}
$$

rounds for strongly connected graphs, where $D$ is the directed diameter, with at most $mn+O(m)$ messages. The same shortest-path DAG and path-count information supports betweenness centrality. For weighted DAGs, longest-length-tree scheduling separates concurrent source computations, yielding exact APSP in $n+O(L)$ rounds, where $L$ is the maximum directed path length in edges [1805.08124].

A different deterministic distributed algorithm handles nonnegative integer weights, including zero weights, using a combined distance–hop scheduling key. For a path of weighted length $d$ and hop length $l$, the key is

$$
\kappa=d\gamma+l,
\qquad
\gamma=\sqrt{\frac{hk}{\Delta}},
$$

where $h$ is the hop bound, $k$ is the number of sources, and $\Delta$ is a distance bound. The additive hop term ensures strict progress even over zero-weight edges. The resulting $(h,k)$-source shortest-path computation takes

$$
2\sqrt{\Delta kh}+k+h
$$

rounds; APSP up to distance $\Delta$ takes

$$
2n\sqrt{\Delta}+2n
$$

rounds.

In the Congest- Clique model, every pair of nodes communicates directly. Classical exact APSP uses $\widetilde O(n^{1/3})$ rounds, while quantum communication gives an algorithm using

$$
O(n^{1/4}\log W)
$$

rounds for directed graphs with integer weights in $[-W,W]$, with high probability [1906.02456]. The algorithm reduces distance products to negative-triangle detection and uses parallel quantum searches whose congestion is controlled by random partitions and replication. In the classical Congested Clique, randomized approximate APSP for weighted undirected graphs can be performed in $O(\log\log\log n)$ rounds with an $O(1)$ approximation. More generally, $O(t)$ rounds yield an

$$
O\!\left((\log n)^{1/2^t}\right)
$$

approximation [2405.02695].

Static parallel APSP also admits a work-depth tradeoff for real-weighted directed graphs. For every $d\in[1,n]$, a deterministic algorithm achieves

$$
\widetilde O\bigl(nm+(n/d)^3\bigr)
$$

work and $\widetilde O(d)$ depth [2101.02311]. The method constructs deterministic hub sets for shortest $d$-hop paths, performs bounded-hop Bellman–Ford computations, solves a dense APSP instance on the hub vertices, and lifts distances through the hub hierarchy. For sparse graphs, choosing $d$ around $n^{1/3}$ makes the work nearly $nm$.

## 4. Dynamic, decremental, and output-sensitive APSP

Dynamic APSP maintains distances while the graph changes. In decremental settings, updates delete vertices or increase incident edge weights. A stronger problem, all-pairs all-shortest-paths (APASP), maintains every shortest-path DAG and the multiplicity of shortest paths, not merely one distance per ordered pair.

For positive-weight directed graphs, APASP can be represented compactly with tuples and triples. A tuple

$$
\tau=(xa,by)
$$

represents paths sharing the first edge $(x,a)$ and last edge $(b,y)$, while a triple $(\tau,wt,count)$ stores the common weight and number of represented paths. The data structure maintains locally shortest paths, shortest-path tuples, extension sets, priority queues, and path multiplicities. The key parameter is

$$
\vstar=
\max_{v\in V}
\{\text{number of edges lying on shortest paths through }v\}.
$$

The decremental algorithm performs cleanup of paths containing the updated vertex and fixup of newly relevant paths. Its amortized update time is

$$
O(\vstar^2\log n),
$$

with space $O(m^*\vstar)$, where $m^*$ is the number of edges lying on at least one shortest path. If every vertex lies on $O(n)$ shortest-path edges, including the case of constantly many shortest paths per ordered pair, the bound becomes $O(n^2\log n)$ per update. The same path-count information supports decremental betweenness centrality [1411.4073].

Fully dynamic exact APSP supports both vertex insertions and deletions. Earlier structures achieved $\widetilde O(n^2)$ amortized update time but used $O(n^3)$ space, while Thorup’s worst-case structure used $\widetilde O(n^{2+3/4})$ update time and supercubic space. Space-efficient deterministic structures reduce the worst-case weighted update time to

$$
\widetilde O(n^{2+5/7})
$$

and the unweighted bound to

$$
\widetilde O(n^{2+3/5}).
$$

A simpler deterministic structure achieves $\widetilde O(n^{2+3/4})$ for weighted graphs and $\widetilde O(n^{2+2/3})$ for unweighted graphs using $\widetilde O(n^2)$ space. A Las Vegas structure achieves $\widetilde O(n^{2+2/3})$ for weighted graphs and $\widetilde O(n^{2.5})$ for unweighted graphs, also with near-quadratic space and tolerance of a non-oblivious adversary [2001.10801].

Dynamic APSP in planar graphs has stronger specialized bounds. For planar directed graphs with positive edge weights and an offline sequence of edge-weight changes, dynamic dense distance graphs can be maintained in $\widetilde O(\sqrt r)$ worst-case update time for an $r$-capped recursive decomposition. FR-Dijkstra answers arbitrary distance queries in $\widetilde O(n/\sqrt r)$ time. Setting $r=n^{2\delta}$ gives

$$
\widetilde O(n^\delta)
\quad\text{update time}
\qquad\text{and}\qquad
\widetilde O(n^{1-\delta})
\quad\text{query time}.
$$

The balanced choice $\delta=1/2$ gives $\widetilde O(\sqrt n)$ for both operations, matching conditional lower bounds up to polylogarithmic factors in the offline setting. The same bound holds online for incremental weight decreases, but not for fully online arbitrary increases and decreases [2606.01809].

Approximate dynamic APSP admits substantially smaller update and query overheads. For undirected nonnegative weighted graphs undergoing fully dynamic edge updates, a deterministic neighborhood-cover and emulator framework achieves a large multiplicative approximation of the form

$$
(\log\log n)^{2^{O(1/\varepsilon^2)}},
$$

with amortized update time $n^{O(\varepsilon)}\log \Lambda$ and distance-query time

$$
2^{O(1/\varepsilon)}\log n\log\log\Lambda,
$$

where $\Lambda$ is the ratio of maximum to minimum edge length. Shortest-path queries additionally require time proportional to the returned path length [2304.09321].

Warm-start methods reuse a previously computed distance matrix after a small modification. Adding a vertex can be handled by computing distances to and from the new vertex using the old matrix, then updating old-old pairs by

$$
SPD(i,j\mid G+p)
=
\min\left(
SPD(i,j\mid G),
SPD(i,p\mid G+p)+SPD(p,j\mid G+p)
\right).
$$

This requires $O(n^2)$ work. Vertex deletion identifies potentially affected ordered pairs using the condition

$$
SPD(i,j\mid G)=SPD(i,k\mid G)+SPD(k,j\mid G),
$$

then selectively reruns Dijkstra; the best case is $O(n^2)$ and the worst case is $O(n^3)$ [2412.15122].

## 5. Approximation, DAG structure, and fine-grained complexity

Approximate APSP is often expressed through multiplicative, additive, or bicriteria guarantees. A multiplicative $\alpha$-approximation returns

$$
d(u,v)\le \widehat d(u,v)\le \alpha d(u,v),
$$

while an additive $+\beta$ approximation satisfies

$$
d(u,v)\le \widehat d(u,v)\le d(u,v)+\beta.
$$

Since $d+\beta\le 2d$ whenever $d\ge\beta$, additive approximations can yield multiplicative $2$-approximations for sufficiently distant pairs.

For unweighted undirected graphs, recent algorithms combine degree decompositions, dominating sets, low-degree residual graphs, and rectangular matrix multiplication. A randomized $(2,0)$-approximation achieves expected time

$$
O(n^{2.03184039}),
$$

and a deterministic version achieves

$$
O(n^{2.07203166}).
$$

The same framework improves additive approximations, including approximately $n^{2.155}$ for $+4$ and $n^{2.103}$ for $+6$ [2309.13225]. A later cluster-decomposition approach obtains randomized bounds of $O(n^{2.22548})$ for $+2$, $O(n^{2.14613})$ for $+4$, and $O(n^{2.102595})$ for $+6$, using constant-diameter clusters and standard fast matrix multiplication rather than bounded-difference min-plus products [2511.04775].

A near-quadratic randomized algorithm gives a factor-$2$ approximation for every pair whose distance is at least a fixed constant $c$, with high probability, in $\widetilde O(n^2)$ time. The construction uses sampled pivots, balls, clusters, low-degree path segments, and rectangular matrix multiplication for dense local neighborhoods. The explicit constant in the analysis is at most $906$ [2607.18714]. This result approaches the $\Omega(n^2)$ output-size bound, but does not establish a factor-$2$ guarantee for all pairs without a distance threshold.

DAGs provide another form of structure. Standard SSSP in a DAG takes $O(n+m)$ time after topological sorting, and running it from every source takes $O(nm+n^2)$. An output-sensitive algorithm instead stores lexicographically first shortest paths in trees $T_v$ rooted at each destination. Its running time is

$$
O\left(
\min\{n^\omega,nm+n^2\log n\}
+
\sum_{v\in V}\operatorname{indeg}(v)|\operatorname{leaf}(T_v)|
\right).
$$

The second term measures the number of independent shortest-path branches. When the trees have few leaves, extensive path sharing reduces the cost; when they are highly branched, the bound approaches the standard $O(nm)$ scale [2108.03455].

Fine-grained complexity treats exact weighted APSP as a source of conditional lower bounds. The APSP conjecture asserts that general weighted APSP cannot be solved in truly subcubic time. Approximation below factor $2$ in unweighted undirected graphs is closely connected to Boolean matrix multiplication. These barriers do not preclude instance-sensitive algorithms. A learning-augmented algorithm can accept, for each pair $(u,v)$, a predicted set of intermediate vertices likely to lie on shortest routes. If $\eta$ counts incorrect or unverifiable pair entries, the cited running time is

$$
O(n^{2.83}+\eta n).
$$

The algorithm remains correct for arbitrary predictions and degrades to the cubic scale when $\eta=\Theta(n^2)$ [2607.00857].

## 6. Implementations, hardware acceleration, and practical limitations

APSP implementations must address both arithmetic work and data movement. Distributed-memory Spark implementations use blocked min-plus products, blocked Floyd–Warshall, or repeated squaring. The strongest Spark design for large undirected weighted graphs uses blocked collect/broadcast operations and shared persistent storage. It handled instances with more than $200{,}000$ vertices on a 1,024-core cluster, but remained slower than an optimized MPI divide-and-conquer implementation and was not fully fault-tolerant because external files lay outside the RDD lineage [1902.04446].

The principal engineering parameters are block size, data partitioning, synchronization frequency, and storage traffic. Scalar Floyd–Warshall exposes $n$ global iterations, while blocked methods reduce this to approximately $n/b$ iterations for block size $b$. Larger blocks reduce synchronization but increase local computation and reduce parallelism. Sparse graph structure is difficult to exploit in dense matrix formulations because absent edges are represented by $\infty$ and all matrix blocks participate in the computation.

Processing-in-memory architectures target the data-movement bottleneck of dense Floyd–Warshall. PIM-FW places specialized bit-serial processing elements inside HBM3 banks and channel-level processing elements near memory controllers. The blocked computation retains the three dependency phases: pivot-tile update, pivot-row and pivot-column update, and off-diagonal tile update. An interleaved tile mapping distributes blocks across channels and bank groups. The architecture performs the dominant min-plus operations in memory while reserving near-memory processing for cross-bank reductions.

In cycle-accurate simulation, PIM-FW reportedly achieves an $18.7$-fold end-to-end speedup and more than a $3{,}200$-fold DRAM-energy reduction over an optimized GPU-only Floyd–Warshall implementation for an $8192\times8192$ distance matrix [2512.18158]. These results are simulation-based and apply to the dense Floyd–Warshall representation; specialized sparse algorithms may remain preferable for genuinely sparse inputs.

Across algorithmic settings, several limitations recur. Exact APSP generally requires $\Omega(n^2)$ output space, and many algorithms require additional matrices or shortest-path representations. Negative cycles make ordinary shortest-path distances undefined. Distributed bounds depend on bandwidth, topology, message size, and whether communication may use underlying undirected links. Dynamic bounds distinguish amortized from worst-case time, online from offline updates, and deterministic from randomized guarantees. Approximation results may depend on graph direction, nonnegative or unweighted edges, distance thresholds, or large hidden constants.

The main unresolved objectives include a general truly subcubic exact algorithm for weighted APSP, a deterministic near-quadratic algorithm for factor-$2$ approximation on all unweighted undirected pairs, sub-$\sqrt n$ fully online dynamic APSP in planar digraphs, and practical implementations whose communication and memory costs match their asymptotic arithmetic bounds.

Source: https://www.emergentmind.com/topics/all-pairs-shortest-paths-apsp