{"id":179,"date":"2026-11-13T12:33:43","date_gmt":"2026-11-13T04:33:43","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-floyd-warshall-closes-all-pairs-distances\/"},"modified":"2026-11-13T21:51:55","modified_gmt":"2026-11-13T13:51:55","slug":"how-floyd-warshall-closes-all-pairs-distances","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-floyd-warshall-closes-all-pairs-distances\/","title":{"rendered":"How Floyd-Warshall closes all-pairs distances"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Floyd-Warshall<\/strong> computes the shortest path between every pair by allowing intermediate vertices in order. After step k, dist[i][j] is the best path that uses only intermediates among the first k vertices. The triple loop is <strong>\u0398(V\u00b3)<\/strong> time and <strong>\u0398(V\u00b2)<\/strong> memory. Negative edges are allowed. A negative value on the diagonal after the loops is a <strong>negative cycle<\/strong>.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">All-pairs distances can be V single-source runs. That is the right reduction when a heap-based Dijkstra is cheap and weights are nonnegative. A dense graph, or a graph with negative edges and no negative cycle, wants a single cubic pass that does not depend on a heap. The inductive object is a path whose intermediate vertices are restricted to a prefix of the vertex list.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A path that is allowed to use vertex k either avoids k, in which case the previous matrix already has it, or it goes from i to k and from k to j using only lower intermediates. Those two pieces are independent once k is the highest intermediate, which is why one matrix, updated in place, is enough if k is the outer index.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Initialized with edge weights, zeros on the diagonal, and infinity elsewhere, the algorithm returns true shortest-path distances whenever no negative cycle exists. Time is \u0398(V\u00b3) regardless of how many edges exist, so a sparse graph with nonnegative weights is usually faster as V runs of Dijkstra. Extra memory is the distance matrix. A predecessor matrix, updated whenever dist[i][k]+dist[k][j] wins, reconstructs one path.<\/p>\n\n\n<p class=\"wp-block-paragraph\">In-place update is correct when the k loop is outermost. Then the values read for intermediate k were finalized at this k or earlier, and a path does not need k twice unless a negative cycle is present. After termination, dist[v][v] &lt; 0 means a negative cycle through v. The algorithm has no separate detection pass.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Number vertices 0..n\u22121. Set dist[i][i] = 0, dist[i][j] to the weight of edge i\u2192j when it exists, and infinity otherwise. Keep the best edge if parallel edges exist.<\/li>\n<li>For k from 0 to n\u22121, for every pair i, j, if dist[i][k] + dist[k][j] &lt; dist[i][j], replace dist[i][j] and optionally set pred[i][j] = pred[k][j].<\/li>\n<li>Add two infinities as infinity, so a missing intermediate does not look like a path.<\/li>\n<li>After the loops, any negative dist[v][v] is a negative cycle. Path reconstruction through that pair is undefined.<\/li>\n<li>Read dist[i][j] as the shortest-path distance. Walk predecessors from j back toward i to recover a path when no negative cycle exists.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The cubic bound counts triples, not edges. A sparse nonnegative instance belongs to repeated Dijkstra, and a sparse instance with negative edges belongs to Johnson, which reweights and then runs Dijkstra. Floyd-Warshall is the dense, simple all-pairs algorithm, including the negative-cycle test on the diagonal.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the k loop is not outermost<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Loop i or j outside k and update one matrix<\/td>\n<td>A value may then use vertex k more than once inside a single pair&#8217;s update, or miss the inductive order. The proof is the outer k.<\/td>\n<\/tr>\n<tr>\n<td>V runs of Dijkstra while a negative edge exists<\/td>\n<td>Dijkstra&#8217;s settled distances are unsafe. The cubic algorithm does not settle a vertex early.<\/td>\n<\/tr>\n<tr>\n<td>Treat a negative diagonal as a usable distance<\/td>\n<td>A negative cycle makes that pair&#8217;s distance unbounded below. The number in the matrix is an artifact of n passes, not a shortest path.<\/td>\n<\/tr>\n<tr>\n<td>Use \u0398(V\u00b3) as a reason to prefer it on a sparse road network<\/td>\n<td>Repeated Dijkstra or Johnson tracks E. The triple loop always pays n\u00b3.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Sparse nonnegative all-pairs distances belong to a Dijkstra run from each vertex. Sparse all-pairs with negative edges and no desire to pay n\u00b3 belong to Johnson&#8217;s reweighting.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script run Floyd\u2013Warshall with k as the outermost index. A missing edge is 999. Both print the distance matrix from vertex 0, then 1, then 2: <code>0 1 3<\/code> \/ <code>999 0 2<\/code> \/ <code>999 999 0<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">INF=999\n# row-major, 3 vertices, edges 0-&gt;1 weight 1 and 1-&gt;2 weight 2\nd=(0 1 999  999 0 2  999 999 0)\nn=3\nat() { echo &quot;${d[$(( $1 * n + $2 ))]}&quot;; }\nfor ((k=0; k&lt;n; k++)); do\n  for ((i=0; i&lt;n; i++)); do\n    for ((j=0; j&lt;n; j++)); do\n      ik=$(at $i $k); kj=$(at $k $j); ij=$(at $i $j)\n      if (( ik + kj &lt; ij )); then d[i*n+j]=$((ik+kj)); fi\n    done\n  done\ndone\necho &quot;${d[0]} ${d[1]} ${d[2]}&quot;\necho &quot;${d[3]} ${d[4]} ${d[5]}&quot;\necho &quot;${d[6]} ${d[7]} ${d[8]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">INF = 999\nd = [\n    [0, 1, INF],\n    [INF, 0, 2],\n    [INF, INF, 0],\n]\nn = 3\nfor k in range(n):\n    for i in range(n):\n        for j in range(n):\n            if d[i][k] + d[k][j] &lt; d[i][j]:\n                d[i][j] = d[i][k] + d[k][j]\nassert d == [[0, 1, 3], [999, 0, 2], [999, 999, 0]]\nfor row in d:\n    print(*row)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Floyd-Warshall fills the all-pairs distance matrix of a small network, and the same triple loop computes a transitive closure if the operation is Boolean. A campus map or a dense tariff table is the right size. A sparse road graph uses Johnson or repeated Dijkstra.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop Floyd-Warshall on a large sparse graph. Keep it for dense graphs, for a short implementation of all-pairs distances, and for a negative-cycle test that falls out of the same matrix.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Floyd-Warshall returns the outer intermediate index and the negative diagonal that reports a cycle. <strong>Floyd-Warshall computes all-pairs distances in \u0398(V\u00b3) time by adding one allowed intermediate at a time, and a negative diagonal is a negative cycle.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Floyd-Warshall computes the shortest path between every pair by allowing intermediate vertices in order. After step k, dist[i][j] is the best path that uses only intermediates among the first k vertices. The triple loop is \u0398(V\u00b3) time and \u0398(V\u00b2) memory. Negative edges are allowed. A negative value&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,32],"tags":[],"class_list":["post-179","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-graphs"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/179","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=179"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/179\/revisions"}],"predecessor-version":[{"id":578,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/179\/revisions\/578"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=179"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=179"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}