Today writes the shortest path The Floyd algorithm (has the translation is called Freud, but this wonderful translation is used to read the good ... ）。

The essence of this algorithm, broadly speaking, is actually DP (Dynamic programming). In fact, supposedly, the algorithm should say what greedy, search, DP, two points of the basic algorithm, but I think too broad things for people who do not have the basis to speak up unclear, or write a comparison of some typical algorithm is better. And this series is C + + code, not too detailed analysis description, those who have time to write again later.

Floyd, find the shortest path between any two points in a graph. The graph has N points, then the algorithm complexity is O (n³), the space complexity is O (N²), programming complexity is very low.

First of all, the basic operation of the I->J, if the current path is not as short as i->k->j, then update the shortest way. This operation is called "slack operation", is a very basic operation in the shortest path algorithm, just like the "swap operation" in the sort, the Floyd, Dijkstra, SPFA are based on this operation. Written code is:

if (D[i][j]<d[i][k]+d[k][j]) d[i][j]=d[i][k]+d[k][j];

The idea of the Floyd algorithm is to update all paths with each point being the middle node (k in the above). For example, for u->v, the shortest path is u->k1->k2->k3->k4->v, assuming k1<k3<k2<k4, then the actual process is:

0, the algorithm initialization, the definition of a D array, the existence of the initial arbitrary two points between the distance, if there is an edge u->v, then d[u][v] = u->v; If there is no edge u->v, then D[u][v] =∞ (in fact, equivalent to the graph of the adjacency matrix, but not the edge to complement the ∞)

1, may wish to set original D[u][v] =∞

2, when k=k1, d[u][k2] = d[u][k1]+d[k1][k2] = u->k1->k2;

3, when K=k3, d[k2][k4] = d[k2][k3]+d[k3][k4] = k2->k3->k4;

4, when k=k2, d[u][k4] = d[u][k2]+d[k2][k4] = u->k1->k2->k3->k4;

5, when k=k4, d[u][v] = d[u][k4]+d[k4][v] = u->k1->k2->k3->k4->v;

6, the algorithm ends, D[u][v] in the final shortest path, all point pairs are so, so after the completion of all the process, any two points of the shortest path is to be obtained.

In fact, in this derivation process, some problems are not taken into account, so the correctness of the algorithm is not fully proved in this article. Time is limited, no longer elaborate, interested students can think, I have time to mention again.

The code is simple, just three lines:

for (int k=1; k<=n;++k) for (int i=1; i<=n;++i) for (int j=1// here means to update the left side with the right, that is, the slack operation

"Algorithm" C + + code Floyd