Qm
Core

Floyd-Warshall All-Pairs Shortest Paths

An algorithm that finds the shortest path between every pair of nodes in a network simultaneously, by repeatedly asking whether routing through one more intermediate node ever beats the best route found so far.

The Floyd-Warshall algorithm computes the shortest distance between every pair of nodes in a weighted graph, for example, the cheapest currency-conversion path between every pair of currencies in an FX network, including indirect routes through intermediate currencies. Instead of running a single-source shortest-path search separately from each starting node, it fills in one distance matrix for all pairs at once.

The core idea is a triple loop: for every possible intermediate node kk, and every pair of nodes (i,j)(i, j), check whether routing from ii to jj through kk is shorter than the best known direct route, that is, update dijmin(dij,dik+dkj)d_{ij} \leftarrow \min(d_{ij}, d_{ik} + d_{kj}). Doing this for every kk from 1 to nn, in order, guarantees that by the end, every pair's distance has considered every possible intermediate node as a potential shortcut. For a graph with nn currencies, this costs O(n3)O(n^3) time, for n=20n = 20 currencies, about 203=8,00020^3 = 8{,}000 update checks, comfortably fast even on modest hardware.

Concretely, if converting USD to EUR directly implies a rate corresponding to a "distance" of 5 (in log-rate terms, so distances add along a path), but USD to JPY to EUR sums to a distance of 4.2, the algorithm updates the USD-EUR entry to reflect the cheaper indirect route the moment JPY is considered as intermediate node kk, this is exactly the check underlying cross-currency triangular-arbitrage detection.

Floyd-Warshall finds shortest paths between all pairs of nodes at once, in O(n3)O(n^3) time, by iteratively checking whether routing through each candidate intermediate node improves on the best distance found so far.

Discussion

Sign in to join the discussion · reading is open to everyone

💡 Discussion rules

  1. Ask and answer about this concept. Off-topic gets removed.
  2. No homework dumps. Show what you tried first.
  3. Corrections are welcome. Cite a source when you claim an error.

Loading discussion…

Related concepts

Practice in interviews

Further reading

  • Cormen et al., Introduction to Algorithms, ch. 25
ShareTwitterLinkedIn