Floyd algorithm
The Floyd algorithm can be used to solve the shortest path problem between any two vertices.
Core formula:
Edge [I] [J] = min {edge [I] [J], edge [I] [k] + edge [k] [J]}.
That is to say, we can relax by inserting the vertex between I and j and comparing the path size.
First, we define a two-dimensional array edge [maxn] [maxn] to store Graph Information.
After the edge array of the graph is initialized
It is equivalent to the distance between any two points that cannot pass through other points.
Code1:
1 // After vertex 2 for (I = 1; I <= N; I ++) 3 for (j = 1; j <= N; j ++) 4 If (E [I] [J]> E [I] [1] + E [1] [J]) E [I] [J] = E [I] [1] + E [1] [J];
In this example, vertex 1 is allowed as the center point to relax the distance and save the result after relaxation.
Code2:
1 // After vertex 2 for (I = 1; I <= N; I ++) 3 for (j = 1; j <= N; j ++) 4 If (E [I] [J]> E [I] [2] + E [2] [J]) E [I] [J] = E [I] [2] + E [2] [J];
Allow vertex 1 and vertex 2 to relax and save as intermediate points. (Not always relaxed !)
.....
Core code of Floyd:
1 for(k=1;k<=n;k++)2 for(i=1;i<=n;i++)3 for(j=1;j<=n;j++)4 if(e[i][j]>e[i][k]+e[k][j])5 e[i][j]=e[i][k]+e[k][j];
The basic idea of this Code is: In the beginning, it is allowed to transit only through vertex 1, and then only through vertex 1 and vertex 2 ...... 1 ~ All vertices on N are transitioned to find the shortest path between any two points. In a word, the shortest distance from vertex I to vertex J is only the first K.
Time Complexity: O (N ^ 3)
Some of the image text is taken from the blog of Aha lei.