请输入您要查询的百科知识:

 

词条 Floyd–Warshall algorithm
释义

  1. History and naming

  2. Algorithm

  3. Example

  4. Behavior with negative cycles

  5. Path reconstruction

      Pseudocode [11] :  

  6. Analysis

  7. Applications and generalizations

  8. Implementations

  9. Comparison with other shortest path algorithms

  10. References

  11. External links

{{Redirect|Floyd's algorithm|cycle detection|Floyd's cycle-finding algorithm|computer graphics|Floyd–Steinberg dithering}}{{Infobox Algorithm
|class=All-pairs shortest path problem (for weighted graphs)
|image=
|caption =
|data=Graph
|time=
|average-time=
|best-time=
|space=
}}{{Tree search algorithm}}

In computer science, the Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles).[1][2] 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 of a relation , 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, and was published in its currently recognized form by Robert Floyd in 1962.[3] However, it is essentially the same as algorithms previously published by Bernard Roy in 1959[4] and also by Stephen Warshall in 1962[5] for finding the transitive closure of a graph,[6] and is closely related to Kleene's algorithm (published in 1956) for converting a deterministic finite automaton into a regular expression.[7] The modern formulation of the algorithm as three nested for-loops was first described by Peter Ingerman, also in 1962.[8]

The algorithm is also known as Floyd's algorithm, the Roy–Warshall algorithm, the Roy–Floyd algorithm, or the WFI algorithm.

Algorithm

The Floyd–Warshall algorithm compares all possible paths through the graph between each pair of vertices. It is able to do this with comparisons in a graph. This is remarkable considering that there may be up to 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 with vertices numbered 1 through . Further consider a function that returns the shortest possible path from to 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 to each using only vertices in .

For each of these pairs of vertices, the could be either

(1) a path that doesn't go through (only uses vertices in the set .)

or

(2) a path that does go through (from to and then from to , both only using intermediate vertices in )

We know that the best path from to that only uses vertices through is defined by , and it is clear that if there were a better path from to to , then the length of this path would be the concatenation of the shortest path from to (only using intermediate vertices in ) and the shortest path from to (only using intermediate vertices in ).

If is the weight of the edge between vertices and , we can define in terms of the following recursive formula: the base case is

and the recursive case is

.

This formula is the heart of the Floyd–Warshall algorithm. The algorithm works by first computing for all pairs for

, then , etc. This process continues until , and we have found the shortest path for all pairs using any intermediate vertices. Pseudocode for this basic version follows:

 1 '''let''' dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity) 2 '''for each''' edge (''u'',''v'') 3    dist[''u''][''v''] ← w(''u'',''v'')  ''// the weight of the edge (''u'',''v'') 4 '''for each''' vertex ''v'' 5    dist[''v''][''v''] ← 0 6 '''for''' ''k'' '''from''' 1 '''to''' |V| 7    '''for''' ''i'' '''from''' 1 '''to''' |V| 8       '''for''' ''j'' '''from''' 1 '''to''' |V| 9          '''if''' dist[''i''][''j''] > dist[''i''][''k''] + dist[''k''][''j'']  10             dist[''i''][''j''] ← dist[''i''][''k''] + dist[''k''][''j''] 11         '''end if'''

Example

The algorithm above is executed on the graph on the left below:

Prior to the first iteration of the outer loop, labeled {{math|1=k = 0}} above, the only known paths correspond to the single edges in the graph. At {{math|1=k = 1}}, paths that go through the vertex 1 are found: in particular, the path [2,1,3] is found, replacing the path [2,3] which has fewer edges but is longer (in terms of weight). At {{math|1=k = 2}}, paths going through the vertices {1,2} are found. The red and blue boxes show how the path [4,2,1,3] is assembled from the two known paths [4,2] and [2,1,3] encountered in previous iterations, with 2 in the intersection. The path [4,2,3] is not considered, because [2,1,3] is the shortest path encountered so far from 2 to 3. At {{math|1=k = 3}}, paths going through the vertices {1,2,3} are found. Finally, at {{math|1=k = 4}}, all shortest paths are found.

The distance matrix at each iteration of {{mvar|k}}, with the updated distances in bold, will be:

{{math|1=k = 0}}{{mvar|j}}
1 2 3 4
{{mvar|i}} 1 0 −2
2 4 0 3
3 0 2
4 −1 0
{{math|1=k = 1}}{{mvar|j}}
1 2 3 4
{{mvar|i}} 1 0 −2
2 4 0 2
3 0 2
4 −1 0
{{math|1=k = 2}}{{mvar|j}}
1 2 3 4
{{mvar|i}} 1 0 −2
2 4 0 2
3 0 2
4 3 −1 1 0
{{math|1=k = 3}}{{mvar|j}}
1 2 3 4
{{mvar|i}} 1 0 −2 0
2 4 0 2 4
3 0 2
4 3 −1 1 0
{{math|1=k = 4}}{{mvar|j}}
1 2 3 4
{{mvar|i}} 1 0 −1 −2 0
2 4 0 2 4
3 5 1 0 2
4 3 −1 1 0
{{clear}}

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 , which form part of a negative cycle, because path-lengths from to 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 , including where ;
  • Initially, the length of the path is zero;
  • A path can only improve upon this if it has length less than zero, i.e. denotes a negative cycle;
  • Thus, after the algorithm, will be negative if there exists a negative-length path from back to .

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.[9] To avoid numerical problems one should check for negative numbers on the diagonal of the path matrix within the inner for loop of the algorithm.[10] 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 can be calculated for each node in time using memory to store each tree which allows us to efficiently reconstruct a path from any two connected vertices.

Pseudocode [11] :

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

Analysis

Let be , the number of vertices. To find all of

(for all and ) from those of

requires operations. Since we begin with

and compute the sequence of matrices , , , , the total number of operations used is

. Therefore, the complexity of the algorithm is .

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 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. Then the addition operation is replaced by logical conjunction (AND) and the minimum operation by logical disjunction (OR).
  • Finding a regular expression denoting the regular language accepted by a finite automaton (Kleene's algorithm, a closely related generalization of the Floyd–Warshall algorithm)[12]
  • Inversion of real matrices (Gauss–Jordan algorithm) [13]
  • 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

Implementations

Implementations are available for many programming languages.

  • For C++, in the boost::graph library
  • For C#, at QuickGraph
  • For C#, at [https://www.nuget.org/packages/QuickGraphPCL/3.6.61114.2 QuickGraphPCL] (A fork of QuickGraph with better compatibility with projects using Portable Class Libraries.)
  • For Java, in the Apache Commons Graph library
  • For JavaScript, in the Cytoscape library
  • For MATLAB, in the Matlab_bgl package
  • For Perl, in the [https://metacpan.org/module/Graph Graph] module
  • For Python, in the SciPy library (module scipy.sparse.csgraph) or NetworkX library
  • For R, in packages [https://cran.r-project.org/web/packages/e1071/index.html e1071] and [https://cran.r-project.org/web/packages/Rfast/index.html Rfast]

Comparison with other shortest path algorithms

The Floyd–Warshall algorithm is a good choice for computing paths between all pairs of vertices in dense graphs, in which most or all pairs of vertices are connected by edges. For sparse graphs with non-negative edge weights, a better choice is to use Dijkstra's algorithm from each possible starting vertex, since the running time of repeated Dijkstra ( using Fibonacci heaps) is better than the running time of the Floyd–Warshall algorithm when is significantly smaller than . 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).[14][15] 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

1. ^{{Introduction to Algorithms|1}} See in particular Section 26.2, "The Floyd–Warshall algorithm", pp. 558–565 and Section 26.4, "A general framework for solving path problems in directed graphs", pp. 570–576.
2. ^{{cite book | author=Kenneth H. Rosen | title=Discrete Mathematics and Its Applications, 5th Edition | publisher = Addison Wesley | year=2003 | isbn=978-0-07-119881-3 }}
3. ^{{cite journal | first = Robert W. | last = Floyd | authorlink = Robert W. Floyd | title = Algorithm 97: Shortest Path | journal = Communications of the ACM | volume = 5 | issue = 6 | page = 345 | date= June 1962 | doi = 10.1145/367766.368168 }}
4. ^{{cite journal | first = Bernard | last = Roy |authorlink=Bernard Roy| title = Transitivité et connexité. | journal = C. R. Acad. Sci. Paris | volume = 249 | pages = 216–218 | year= 1959 }}
5. ^{{cite journal | first = Stephen | last = Warshall | title = A theorem on Boolean matrices | journal = Journal of the ACM | volume = 9 | issue = 1 | pages = 11–12 | date= January 1962 | doi = 10.1145/321105.321107 }}
6. ^{{mathworld|id=Floyd-WarshallAlgorithm | title = Floyd-Warshall Algorithm}}
7. ^{{cite book | authorlink = Stephen Cole Kleene | first = S. C. | last = Kleene | chapter = Representation of events in nerve nets and finite automata | title = Automata Studies | editor = C. E. Shannon and J. McCarthy | pages = 3–42 | publisher = Princeton University Press | year= 1956 }}
8. ^{{cite journal | first = Peter Z. | last = Ingerman | title = Algorithm 141: Path Matrix | journal = Communications of the ACM | volume = 5 | number = 11 | page = 556 | date = November 1962 | doi = 10.1145/368996.369016 }}
9. ^{{cite web | first = Dorit | last = Hochbaum | authorlink = Dorit S. Hochbaum | url = http://www.ieor.berkeley.edu/~hochbaum/files/ieor266-2014.pdf | title = Section 8.9: Floyd-Warshall algorithm for all pairs shortest paths | work = Lecture Notes for IEOR 266: Graph Algorithms and Network Flows | date = 2014 | format = PDF | publisher = Department of Industrial Engineering and Operations Research, University of California, Berkeley}}
10. ^{{cite journal | title = The Floyd–Warshall algorithm on graphs with negative cycles | author = Stefan Hougardy | journal = Information Processing Letters | url = http://www.sciencedirect.com/science/article/pii/S002001901000027X | volume = 110 | number = 8-9 | date = April 2010 | pages = 279–281 | doi=10.1016/j.ipl.2010.02.001}}
11. ^https://books.goalkicker.com/AlgorithmsBook/
12. ^{{citation|title=Handbook of Graph Theory|series=Discrete Mathematics and Its Applications|first1=Jonathan L.|last1=Gross|first2=Jay|last2=Yellen|publisher=CRC Press|year=2003|page=65|url=https://books.google.com/books?id=mKkIGIea_BkC&pg=PA65|isbn=9780203490204}}.
13. ^{{cite journal | title = Algebraic Structures for Transitive Closure | first = Rafael | last = Penaloza|citeseerx = 10.1.1.71.7650}}
14. ^{{citation | last = Zwick | first = Uri | authorlink = Uri Zwick | date = May 2002 | doi = 10.1145/567112.567114 | issue = 3 | journal = Journal of the ACM | pages = 289–317 | title = All pairs shortest paths using bridging sets and rectangular matrix multiplication | volume = 49| arxiv = cs/0008011}}.
15. ^{{citation | last = Chan | first = Timothy M. | authorlink = Timothy M. Chan | date = January 2010 | doi = 10.1137/08071990x | issue = 5 | journal = SIAM Journal on Computing | pages = 2075–2089 | title = More algorithms for all-pairs shortest paths in weighted graphs | volume = 39| citeseerx = 10.1.1.153.6864 }}.

External links

{{commons category|Floyd-Warshall algorithm}}
  • Interactive animation of the Floyd–Warshall algorithm
  • [https://www-m9.ma.tum.de/graph-algorithms/spp-floyd-warshall/index_en.html Interactive animation of the Floyd–Warshall algorithm (Technical University of Munich)]
{{DEFAULTSORT:Floyd-Warshall algorithm}}

5 : Graph algorithms|Routing algorithms|Polynomial-time problems|Articles with example pseudocode|Dynamic programming

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/11/11 11:19:34