"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)