Shortest path (i)-floyd-warshall (algorithm with only five elements)

Source: Internet
Author: User

"multi-source Shortest path"-calculates the shortest path between any two cities.

There are 8 highways in 4 cities, and the numbers on the highways indicate the length of the road. The road is one-way. We now need to find the shortest path between any of the two cities, that is, to find the shortest path between any two points. This problem is called the "multi-source Shortest path" problem.


Using the 4*4 matrix to store the information of the graph, the two-dimensional array e is stored.


The shortest path between two points can be calculated by DFS and BFS. So n^2 the depth or breadth of the first search, that is, every two points of a depth or breadth first search, you can find the shortest path between any two points.


The Floyd-warshall algorithm, the core code implementation is very simple, only 5 lines:

The outside K-loop is all vertices can relay.


Basic idea:

At the beginning, only the 1th vertices are allowed to relay, then only the 1 and 2nd vertices are allowed to relay .... The shortest path between any two points is allowed through all vertices of the 1~n number. Overview: The shortest path from the I-Vertex to the J-Vertex passes through the top K points only.



Input data:


Operation Result:


The time complexity of the floyd-warshall algorithm is O (n^3)
.
However, the Floyd-warshall algorithm cannot solve a graph with a "negative weight loop" (or a "negative weight loop") because there is no shortest path to a graph with a "negative weight loop".



There is no shortest path from vertex number 1th to vertex 3rd because 1-2-3-1-2-3-..... In such a path, the shortest path will be reduced by 1 for every round of such a loop, and will never find the shortest path.



Shortest path (i)-floyd-warshall (algorithm with only five elements)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.