Article Directory
1 Basic principles
The Floyd algorithm is an algorithm for solving the shortest path from all vertices to all vertices in a cyclic graph , and the algorithm complexity is O(n 3 ).
The main idea is to use each vertex as a transit, compare the size relationship with the original path, and update the matrix.
D 0 [v] [w] = min {D - 1 [v] [w], D - 1 [v] [0] + D - 1 [0] [w]} D ^ 0 [v] [w] = min \ {D ^ {- 1} [v] [w], D ^ {- 1} [v] [0] + D ^ {- 1} [0] [w] \} D0[v][w]=m i n { D−1[v][w],D- 1 [v][0]+D−1[0][w]}
2 code
typedef int Patharc[MAXVEX][MAXVEX];
typedef int ShortPathTable[MAXVEX][MAXVEX];
void ShortestPath_Floyd(MGraph G, Patharc *P, ShortPathTable *D)
{
int v,w,k;
for(v=0; v<G.numVertexes; ++v) /* 初始化D与P */
{
for(w=0; w<G.numVertexes; ++w)
{
(*D)[v][w]=G.arc[v][w]; /* D[v][w]值即为对应点间的权值 */
(*P)[v][w]=w; /* 初始化P */
}
}
for(k=0; k<G.numVertexes; ++k)
{
for(v=0; v<G.numVertexes; ++v)
{
for(w=0; w<G.numVertexes; ++w)
{
if ((*D)[v][w]>(*D)[v][k]+(*D)[k][w])
{
/* 如果经过下标为k顶点路径比原两点间路径更短 */
(*D)[v][w]=(*D)[v][k]+(*D)[k][w];/* 将当前两点间权值设为更小的一个 */
(*P)[v][w]=(*P)[v][k];/* 路径设置为经过下标为k的顶点 */
}
}
}
}
}