Floyd–Warshall algorithm
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to practical disciplines (includi ...
, the Floyd–Warshall algorithm (also known as Floyd's algorithm, the Roy–Warshall algorithm, the Roy–Floyd algorithm, or the WFI algorithm) is an
algorithm In mathematics and computer science, an algorithm () is a finite sequence of rigorous instructions, typically used to solve a class of specific problems or to perform a computation. Algorithms are used as specifications for performing ...
for finding shortest paths in a directed
weighted graph This is a glossary of graph theory. Graph theory is the study of graphs, systems of nodes or vertices connected in pairs by lines or edges. Symbols A B ...
with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find the lengths (summed weights) of shortest paths between all pairs of vertices. Although it does not return details of the paths themselves, it is possible to reconstruct the paths with simple modifications to the algorithm. Versions of the algorithm can also be used for finding the
transitive closure In mathematics, the transitive closure of a binary relation on a set is the smallest relation on that contains and is transitive. For finite sets, "smallest" can be taken in its usual sense, of having the fewest related pairs; for infinite ...
of a relation R, or (in connection with the Schulze voting system) widest paths between all pairs of vertices in a weighted graph.


History and naming

The Floyd–Warshall algorithm is an example of
dynamic programming Dynamic programming is both a mathematical optimization method and a computer programming method. The method was developed by Richard Bellman in the 1950s and has found applications in numerous fields, from aerospace engineering to economics. ...
, and was published in its currently recognized form by Robert Floyd in 1962. However, it is essentially the same as algorithms previously published by Bernard Roy in 1959 and also by Stephen Warshall in 1962 for finding the transitive closure of a graph, and is closely related to Kleene's algorithm (published in 1956) for converting a
deterministic finite automaton In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)—also known as deterministic finite acceptor (DFA), deterministic finite-state machine (DFSM), or deterministic finite-state autom ...
into a
regular expression A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" ...
. The modern formulation of the algorithm as three nested for-loops was first described by Peter Ingerman, also in 1962.


Algorithm

The Floyd–Warshall algorithm compares all possible paths through the graph between each pair of vertices. It is able to do this with \Theta(, V, ^3) comparisons in a graph, even though there may be up to \Omega (, V, ^2) edges in the graph, and every combination of edges is tested. It does so by incrementally improving an estimate on the shortest path between two vertices, until the estimate is optimal. Consider a graph G with vertices V numbered 1 through N. Further consider a function \mathrm(i,j,k) that returns the shortest possible path (if one exists) from i to j using vertices only from the set \ as intermediate points along the way. Now, given this function, our goal is to find the shortest path from each i to each j using ''any'' vertex in \. For each of these pairs of vertices, the \mathrm(i,j,k) could be either :(1) a path that does not go through k (only uses vertices in the set \.) or :(2) a path that does go through k (from i to k and then from k to j, both only using intermediate vertices in \) We know that the best path from i to j that only uses vertices 1 through k-1 is defined by \mathrm(i,j,k-1), and it is clear that if there was a better path from i to k to j, then the length of this path would be the concatenation of the shortest path from i to k (only using intermediate vertices in \) and the shortest path from k to j (only using intermediate vertices in \). If w(i,j) is the weight of the edge between vertices i and j, we can define \mathrm(i,j,k) in terms of the following
recursive Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
formula: the base case is : \mathrm(i,j,0) = w(i,j) and the recursive case is : \mathrm(i,j,k) = :: \mathrm\Big(\mathrm(i,j,k-1), ::: \mathrm(i,k,k-1)+\mathrm(k,j,k-1)\Big). This formula is the heart of the Floyd–Warshall algorithm. The algorithm works by first computing \mathrm(i,j,k) for all (i,j) pairs for k=1, then k=2, and so on. This process continues until k=N, and we have found the shortest path for all (i,j) pairs using any intermediate vertices. Pseudocode for this basic version follows: let dist be a , V, × , V, array of minimum distances initialized to ∞ (infinity) for each edge (''u'', ''v'') do dist 'u''''v''] ← w(''u'', ''v'') ''// The weight of the edge (''u'', ''v'')'' for each vertex ''v'' do dist 'v''''v''] ← 0 for ''k'' from 1 to , V, for ''i'' from 1 to , V, for ''j'' from 1 to , V, if dist 'i''''j''] > dist 'i''''k''] + dist 'k''''j''] dist 'i''''j''] ← dist 'i''''k''] + dist 'k''''j''] end if


Example

The algorithm above is executed on the graph on the left below: Prior to the first recursion of the outer loop, labeled above, the only known paths correspond to the single edges in the graph. At , paths that go through the vertex 1 are found: in particular, the path ,1,3is found, replacing the path ,3which has fewer edges but is longer (in terms of weight). At , paths going through the vertices are found. The red and blue boxes show how the path ,2,1,3is assembled from the two known paths ,2and ,1,3encountered in previous iterations, with 2 in the intersection. The path ,2,3is not considered, because ,1,3is the shortest path encountered so far from 2 to 3. At , paths going through the vertices are found. Finally, at , all shortest paths are found. The distance matrix at each iteration of , with the updated distances in bold, will be:


Behavior with negative cycles

A negative cycle is a cycle whose edges sum to a negative value. There is no shortest path between any pair of vertices i, j which form part of a negative cycle, because path-lengths from i to j can be arbitrarily small (negative). For numerically meaningful output, the Floyd–Warshall algorithm assumes that there are no negative cycles. Nevertheless, if there are negative cycles, the Floyd–Warshall algorithm can be used to detect them. The intuition is as follows: * The Floyd–Warshall algorithm iteratively revises path lengths between all pairs of vertices (i,j), including where i=j; * Initially, the length of the path (i,i) is zero; * A path ,k,\ldots,i/math> can only improve upon this if it has length less than zero, i.e. denotes a negative cycle; * Thus, after the algorithm, (i,i) will be negative if there exists a negative-length path from i back to i. Hence, to detect negative cycles using the Floyd–Warshall algorithm, one can inspect the diagonal of the path matrix, and the presence of a negative number indicates that the graph contains at least one negative cycle. During the execution of the algorithm, if there is a negative cycle, exponentially large numbers can appear, as large as \Omega(\cdot6^ w_), where w_ is the largest absolute value of a negative edge in the graph. To avoid overflow/underflow problems one should check for negative numbers on the diagonal of the path matrix within the inner for loop of the algorithm. Obviously, in an undirected graph a negative edge creates a negative cycle (i.e., a closed walk) involving its incident vertices. Considering all edges of the above example graph as undirected, e.g. the vertex sequence 4 – 2 – 4 is a cycle with weight sum −2.


Path reconstruction

The Floyd–Warshall algorithm typically only provides the lengths of the paths between all pairs of vertices. With simple modifications, it is possible to create a method to reconstruct the actual path between any two endpoint vertices. While one may be inclined to store the actual path from each vertex to each other vertex, this is not necessary, and in fact, is very costly in terms of memory. Instead, the
shortest-path tree In mathematics and computer science, a shortest-path tree rooted at a vertex ''v'' of a connected, undirected graph ''G'' is a spanning tree ''T'' of ''G'', such that the path distance from root ''v'' to any other vertex ''u'' in ''T'' is the short ...
can be calculated for each node in \Theta(, E, ) time using \Theta(, V, ) memory to store each tree which allows us to efficiently reconstruct a path from any two connected vertices.


Pseudocode

let dist be a , V, \times , V, array of minimum distances initialized to \infty (infinity) let next be a , V, \times , V, array of vertex indices initialized to null procedure ''FloydWarshallWithPathReconstruction''() is for each edge (u, v) do dist v] ← w(u, v) ''// The weight of the edge (u, v)'' next v] ← v for each vertex v do dist v] ← 0 next v] ← v for k from 1 to , V, do ''// standard Floyd-Warshall implementation'' for i from 1 to , V, for j from 1 to , V, if dist j] > dist k] + dist j] then dist j] ← dist k] + dist j] next j] ← next k] procedure Path(u, v) if next v] = null then return [] path ← [u] while ''u'' ≠ ''v'' u ← next v] path.append(u) return path


Time analysis

Let n be , V, , the number of vertices. To find all n^2 of \mathrm(i,j,k) (for all i and j) from those of \mathrm(i,j,k-1) requires 2n^2 operations. Since we begin with \mathrm(i,j,0) = \mathrm(i,j) and compute the sequence of n matrices \mathrm(i,j,1), \mathrm(i,j,2), \ldots, \mathrm(i,j,n), the total number of operations used is n \cdot 2n^2 = 2n^3. Therefore, the complexity of the algorithm is \Theta(n^3).


Applications and generalizations

The Floyd–Warshall algorithm can be used to solve the following problems, among others: * Shortest paths in directed graphs (Floyd's algorithm). *
Transitive closure In mathematics, the transitive closure of a binary relation on a set is the smallest relation on that contains and is transitive. For finite sets, "smallest" can be taken in its usual sense, of having the fewest related pairs; for infinite ...
of directed graphs (Warshall's algorithm). In Warshall's original formulation of the algorithm, the graph is unweighted and represented by a Boolean
adjacency matrix In graph theory and computer science, an adjacency matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph. In the special case of a finite simp ...
. Then the addition operation is replaced by
logical conjunction In logic, mathematics and linguistics, And (\wedge) is the truth-functional operator of logical conjunction; the ''and'' of a set of operands is true if and only if ''all'' of its operands are true. The logical connective that represents thi ...
(AND) and the minimum operation by
logical disjunction In logic, disjunction is a logical connective typically notated as \lor and read aloud as "or". For instance, the English language sentence "it is raining or it is snowing" can be represented in logic using the disjunctive formula R \lor ...
(OR). * Finding a
regular expression A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" ...
denoting the
regular language In theoretical computer science and formal language theory, a regular language (also called a rational language) is a formal language that can be defined by a regular expression, in the strict sense in theoretical computer science (as opposed to ...
accepted by a finite automaton ( Kleene's algorithm, a closely related generalization of the Floyd–Warshall algorithm) * Inversion of
real Real may refer to: Currencies * Brazilian real (R$) * Central American Republic real * Mexican real * Portuguese real * Spanish real * Spanish colonial real Music Albums * ''Real'' (L'Arc-en-Ciel album) (2000) * ''Real'' (Bright album) (2010) ...
matrices Matrix most commonly refers to: * ''The Matrix'' (franchise), an American media franchise ** ''The Matrix'', a 1999 science-fiction action film ** "The Matrix", a fictional setting, a virtual reality environment, within ''The Matrix'' (franchis ...
( Gauss–Jordan algorithm) * Optimal routing. In this application one is interested in finding the path with the maximum flow between two vertices. This means that, rather than taking minima as in the pseudocode above, one instead takes maxima. The edge weights represent fixed constraints on flow. Path weights represent bottlenecks; so the addition operation above is replaced by the minimum operation. * Fast computation of Pathfinder networks. * Widest paths/Maximum bandwidth paths * Computing canonical form of difference bound matrices (DBMs) * Computing the similarity between graphs * Transitive closure in AND/OR/threshold graphs.


Implementations

Implementations are available for many
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s. * For
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, in th
boost::graph
library * For C#, a
QuickGraph
* For C#, a
QuickGraphPCL
(A fork of QuickGraph with better compatibility with projects using Portable Class Libraries.) * For
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
, in th
Apache Commons Graph
library * For
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
, in the Cytoscape library * For
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
, in th
Graphs.jl
package * For
MATLAB MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementa ...
, in th
Matlab_bgl
package * For
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, in th
Graph
module * For
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, in the
SciPy SciPy (pronounced "sigh pie") is a free and open-source Python library used for scientific computing and technical computing. SciPy contains modules for optimization, linear algebra, integration, interpolation, special functions, FFT, ...
library (modul
scipy.sparse.csgraph
or NetworkX library * For R, in package
e1071
an


Comparison with other shortest path algorithms

The Floyd–Warshall algorithm is a good choice for computing paths between all pairs of vertices in
dense graph In mathematics, a dense graph is a graph in which the number of edges is close to the maximal number of edges (where every pair of vertices is connected by one edge). The opposite, a graph with only a few edges, is a sparse graph. The distinctio ...
s, in which most or all pairs of vertices are connected by edges. For
sparse graph In mathematics, a dense graph is a graph in which the number of edges is close to the maximal number of edges (where every pair of vertices is connected by one edge). The opposite, a graph with only a few edges, is a sparse graph. The distinction ...
s with non-negative edge weights, lower asymptotic complexity can be obtained by running
Dijkstra's algorithm Dijkstra's algorithm ( ) is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years ...
from each possible starting vertex, since the worst-case running time of repeated Dijkstra (O(, E, , V, +, V, ^2\log, V, ) using Fibonacci heaps) is smaller than the O(, V, ^3) running time of the Floyd–Warshall algorithm when , E, is significantly smaller than , V, ^2. For sparse graphs with negative edges but no negative cycles, Johnson's algorithm can be used, with the same asymptotic running time as the repeated Dijkstra approach. There are also known algorithms using fast matrix multiplication to speed up all-pairs shortest path computation in dense graphs, but these typically make extra assumptions on the edge weights (such as requiring them to be small integers).. In addition, because of the high constant factors in their running time, they would only provide a speedup over the Floyd–Warshall algorithm for very large graphs.


References


External links


Interactive animation of the Floyd–Warshall algorithm


{{DEFAULTSORT:Floyd-Warshall algorithm Graph algorithms Routing algorithms Polynomial-time problems Articles with example pseudocode Dynamic programming Graph distance