{
  "id": "floyd-warshall-algorithm",
  "title": "Floyd–Warshall Algorithm",
  "lang": "en",
  "source_lang": "en",
  "summary": "The Floyd–Warshall algorithm computes shortest-path distances between all pairs of vertices in a weighted graph using dynamic programming.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Floyd's algorithm",
    "Roy–Floyd algorithm",
    "Roy–Warshall algorithm",
    "Roy–Floyd–Warshall algorithm"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/floyd-warshall-algorithm/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/floyd-warshall-algorithm/",
      "json": "https://aiwiki.page/zh/floyd-warshall-algorithm.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The Floyd–Warshall algorithm is an algorithm for solving the all-pairs shortest-path problem in a weighted graph. It uses dynamic programming to compute a matrix of shortest-path distances, progressively allowing more vertices to serve as intermediate stops. For a graph with \\(n\\) vertices, its standard implementation takes \\(\\Theta(n^3)\\) time and \\(\\Theta(n^2)\\) space. It supports directed graphs and negative edge weights, provided that no negative-weight cycle lies on a route for which a finite shortest-path distance is required."
    },
    {
      "heading": "Problem and representation",
      "text": "Let \\(G=(V,E)\\) be a directed graph whose vertices are numbered \\(1,\\ldots,n\\). Each edge \\((i,j)\\) has a weight \\(w(i,j)\\), representing a cost, distance, or other additive quantity. The task is to determine the minimum total weight of a route from every vertex \\(i\\) to every vertex \\(j\\).\n\nThe algorithm stores these values in an \\(n\\times n\\) matrix. Initially:\n\n- Each diagonal entry is zero, representing the empty path from a vertex to itself.\n- Each existing edge contributes its weight to the corresponding entry.\n- An entry is \\(+\\infty\\) if there is no direct edge.\n- If parallel edges exist, only their minimum weight is needed.\n- A negative-weight self-loop must be preserved rather than overwritten with zero.\n\nEquivalently, initialize all entries to \\(+\\infty\\), set the diagonal to zero, and then take the minimum with every edge weight.\n\nUndirected graphs can be represented by including both directions of each edge. However, a negative-weight undirected edge permits a negative closed walk by traversing the edge in both directions. Consequently, ordinary shortest-walk distances are unbounded below for pairs that can reach and leave that edge."
    },
    {
      "heading": "Dynamic programming recurrence",
      "text": "The essential idea is to restrict which vertices may appear inside a path, excluding its two endpoints.\n\nDefine \\(D^{(k)}_{ij}\\) as the shortest distance from \\(i\\) to \\(j\\) when intermediate vertices may only come from the set \\(\\{1,\\ldots,k\\}\\). The initial matrix \\(D^{(0)}\\) contains direct-edge distances and the zero-length diagonal paths.\n\nWhen vertex \\(k\\) becomes available as an intermediate vertex, a shortest path either:\n\n- Does not use \\(k\\), so its distance remains \\(D^{(k-1)}_{ij}\\); or\n- Uses \\(k\\), splitting into a path from \\(i\\) to \\(k\\) and another from \\(k\\) to \\(j\\).\n\nThis gives the recurrence\n\n\\[D^{(k)}_{ij} = \\min\\left( D^{(k-1)}_{ij}, D^{(k-1)}_{ik}+D^{(k-1)}_{kj} \\right).\\]\n\nAfter processing all \\(n\\) vertices, \\(D^{(n)}\\) contains all shortest-path distances, assuming there are no negative-weight cycles.\n\nThe correctness argument uses a loop invariant: after iteration \\(k\\), the matrix contains optimal distances among paths whose intermediate vertices belong to the first \\(k\\) vertices. In the absence of negative cycles, a shortest route can be chosen without repeated vertices, which justifies splitting a route at a single occurrence of \\(k\\)."
    },
    {
      "heading": "Standard implementation",
      "text": "The recurrence appears to require a separate matrix for every stage, but the standard algorithm updates one matrix in place. The following pseudocode includes reachability checks to avoid adding an infinity sentinel:\n\ndist = n × n matrix filled with INF\n\nfor i = 1 to n:\n    dist[i][i] = 0\n\nfor each edge (u, v, weight):\n    dist[u][v] = min(dist[u][v], weight)\n\nfor k = 1 to n:\n    for i = 1 to n:\n        if dist[i][k] == INF:\n            continue\n        for j = 1 to n:\n            if dist[k][j] == INF:\n                continue\n\n            candidate = dist[i][k] + dist[k][j]\n            if candidate < dist[i][j]:\n                dist[i][j] = candidate\n\nWithout negative cycles, the pivot diagonal \\(dist[k][k]\\) remains zero. Updating through \\(k\\) therefore does not change the pivot row or column, making in-place evaluation consistent with the recurrence.\n\nThe loop over \\(k\\) must remain the outermost loop in this standard one-pass formulation. The loops over \\(i\\) and \\(j\\) may be exchanged. Moving \\(k\\) inside either of them generally breaks the dynamic programming invariant and may produce incorrect results.\n\nExample\n\nConsider three vertices with directed edges \\(1\\to2\\) of weight \\(4\\), \\(2\\to3\\) of weight \\(-2\\), and \\(1\\to3\\) of weight \\(5\\). The initial matrix is\n\n\\[D^{(0)}= \\begin{pmatrix} 0 & 4 & 5\\\\ +\\infty & 0 & -2\\\\ +\\infty & +\\infty & 0 \\end{pmatrix}.\\]\n\nWhen vertex \\(2\\) becomes available as an intermediate vertex, the algorithm discovers\n\n\\[D_{13}=\\min(5,4+(-2))=2.\\]\n\nThe resulting matrix is\n\n\\[D= \\begin{pmatrix} 0 & 4 & 2\\\\ +\\infty & 0 & -2\\\\ +\\infty & +\\infty & 0 \\end{pmatrix}.\\]\n\nThus, the shortest route from \\(1\\) to \\(3\\) goes through \\(2\\), despite the existence of a direct edge."
    },
    {
      "heading": "Negative cycles",
      "text": "Negative edges alone do not invalidate the algorithm. A negative cycle, whose edge weights sum to a negative value, causes a different problem: repeatedly traversing it makes a route's total weight arbitrarily small.\n\nAfter the standard computation, a negative diagonal entry,\n\n\\[dist[t][t]<0,\\]\n\nindicates the presence of a negative cycle. A graph contains a negative cycle if and only if at least one diagonal entry is negative after Floyd–Warshall completes, assuming exact arithmetic.\n\nNot every source–destination pair is necessarily affected. The distance from \\(i\\) to \\(j\\) is unbounded below if there is some vertex \\(t\\) such that\n\n\\[dist[i][t]<+\\infty,\\qquad dist[t][t]<0,\\qquad dist[t][j]<+\\infty.\\]\n\nSuch pairs can be marked as having distance \\(-\\infty\\). This marking is a separate postprocessing step; the ordinary relaxation loop does not itself produce a complete matrix of negative-infinity values.\n\nAn implementation must distinguish three outcomes:\n\n- A finite shortest-path distance.\n- \\(+\\infty\\), meaning the destination is unreachable.\n- \\(-\\infty\\), meaning reachable negative cycles make the route cost unbounded below."
    },
    {
      "heading": "Reconstructing paths",
      "text": "The distance matrix alone does not directly record the corresponding routes. Path reconstruction can be supported with an additional matrix, often called a next-hop matrix.\n\nFor each direct edge \\(i\\to j\\), initialize \\(next[i][j]=j\\). Whenever a strict improvement through \\(k\\) is found, update\n\n\\[next[i][j]=next[i][k].\\]\n\nTo reconstruct a route from \\(i\\) to \\(j\\), repeatedly follow the next-hop entry toward \\(j\\). Unreachable pairs have no next hop, and pairs affected by negative cycles do not have a finite shortest route.\n\nUsing strict improvement avoids unnecessary changes between equal-length alternatives. The extra matrix requires \\(\\Theta(n^2)\\) space, and reconstructing one finite shortest path takes time proportional to the number of vertices it contains."
    },
    {
      "heading": "Complexity and practical considerations",
      "text": "The standard three nested loops perform \\(\\Theta(n^3)\\) distance comparisons. Its time complexity does not improve merely because the input graph has few edges. The distance matrix requires \\(\\Theta(n^2)\\) space, whether or not actual paths are also stored.\n\nThese bounds count arithmetic and comparisons as constant-time operations. If weights require arbitrary-precision arithmetic, the cost of operating on their representations must also be considered.\n\nSeveral implementation details are important:\n\n- Infinity representation: A finite sentinel must exceed every relevant finite distance. Sentinel values should not be added as though they were ordinary weights.\n- Overflow: Even finite operands may produce integer overflow, especially when negative cycles cause repeated decreases.\n- Floating-point arithmetic: Rounding can affect comparisons and the classification of nearly zero-weight cycles.\n- Memory access: The contiguous traversal of matrix rows can improve CPU cache utilization.\n- Blocking: Partitioning the matrix into tiles can improve locality, but pivot tiles and dependent row and column tiles must be processed in an order that preserves dependencies.\n- Parallel execution: Parallel computing can accelerate updates within appropriately synchronized stages. Arbitrarily distributing all iterations without respecting pivot dependencies is not equivalent to the algorithm."
    },
    {
      "heading": "Related algorithms and extensions",
      "text": "Warshall's transitive-closure algorithm\n\nReplacing numerical distances with Boolean reachability gives the closely related algorithm for transitive closure:\n\n\\[R_{ij} \\leftarrow R_{ij}\\lor(R_{ik}\\land R_{kj}).\\]\n\nHere, \\(R_{ij}\\) records whether \\(j\\) is reachable from \\(i\\). Initializing the diagonal to true includes zero-length paths and produces reflexive transitive closure; leaving it initially false instead records reachability by positive-length paths, with diagonal entries becoming true when cycles exist.\n\nThe numerical shortest-path version uses minimum and addition where the Boolean version uses logical OR and AND.\n\nComparison with other shortest-path methods\n\nDijkstra's algorithm solves the single-source problem with nonnegative edge weights. Repeating it from every vertex is often preferable on sparse graphs.\n\nThe Bellman–Ford algorithm permits negative edges and detects reachable negative cycles from a single source, but repeating it for all sources is often more expensive than Floyd–Warshall.\n\nJohnson's algorithm combines Bellman–Ford reweighting with repeated Dijkstra searches. It supports negative edges when there are no negative cycles and is often better suited to sparse all-pairs problems.\n\nFloyd–Warshall remains useful for dense graphs, moderate-sized inputs, and applications requiring a complete distance matrix. Examples include distance-table preprocessing, analysis of weighted networks, and checking systems of difference constraints."
    },
    {
      "heading": "Historical development",
      "text": "The algorithm's history includes several closely related formulations. Bernard Roy published a related path-finding method in 1959. In 1962, Stephen Warshall published a Boolean-matrix algorithm for transitive closure, while Robert W. Floyd published the numerical shortest-path formulation.\n\nThe compound name Floyd–Warshall reflects the shared intermediate-vertex recurrence. Names including Roy acknowledge the earlier contribution, although naming conventions vary across textbooks and software libraries."
    }
  ],
  "links": [
    "algorithm",
    "shortest-path-problem",
    "graph-theory",
    "dynamic-programming",
    "matrix",
    "loop-invariant",
    "pseudocode",
    "time-complexity",
    "space-complexity",
    "integer-overflow",
    "cpu-cache",
    "parallel-computing",
    "transitive-closure",
    "dijkstra-algorithm",
    "bellman-ford-algorithm"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}