介绍
Floyd-Warshall的算法也是运用动态规划来实现的最短路径的一种方法。
实现
typedef int (*Metrix)[VERTEX_NUMBER];
void printfMatrix(Metrix graphmetrix)
{
for (int x = 0; x < VERTEX_NUMBER; ++ x)
{
for (int y = 0; y < VERTEX_NUMBER; ++ y)
{
cout << "\t" << graphmetrix[x][y] << " ";
}
cout << endl;
}
cout << endl;
}
int getSentinel()
{
return 0x7fffffff;
}
以上是辅助函数用来输出矩阵。
Metrix floydWarshall(Metrix graph)
{
const int n = VERTEX_NUMBER;
int *tmp = new int[n * n];
Metrix c = (int(*)[n])tmp;
memcpy(c, graph, n * n * sizeof(4));
tmp = new int[n * n];
Metrix p = (int(*)[n])tmp;
memcpy(p, graph, n * n * sizeof(4));
tmp = new int[n * n];
Metrix precursor_graph = (int(*)[n])tmp;
for (int i = 0; i < n; ++ i)
{
for (int j = 0; j < n; ++ j)
{
if (i != j && graph[i][j] != getSentinel())
{
precursor_graph[i][j] = i + 1;
}else
{
precursor_graph[i][j] = 0;
}
}
}
printfMatrix(precursor_graph);
for (int k = 0; k < n; ++ k)
{
for (int i = 0; i < n; ++ i)
{
for (int j = 0; j < n; ++ j)
{
if (getSentinel() != c[i][k] && getSentinel() != c[k][j])
{
p[i][j] = std::min(c[i][j], c[i][k] + c[k][j]);
if (c[i][j] <= c[i][k] + c[k][j])
{
precursor_graph[i][j] = precursor_graph[i][j];
}else
precursor_graph[i][j] = precursor_graph[k][j];
}
}
}
cout << "shortest path: " << endl;
printfMatrix(p);
cout << "precursor sub graph: " << endl;
printfMatrix(precursor_graph);
memcpy(c, p, n * n * sizeof(4));
}
return c;
}
在Floyd-Warshall算法中,采用的是自底而上的办法来计算最短路径权重,每次使用前一个的计算结果值来得出当前最短路径权重值。首先初始化一个和原图一样的矩阵结构,并初始化一个结果矩阵也和原图保持一致。接着初始化一个前趋子图矩阵,里面保存i->j的某条最短路径中结点j的前趋结点。
而我们可以用下面的程式来验证,使用如下的图来运行Floyd-Warshall算法:
int _tmain(int argc, _TCHAR* argv[])
{
copyright();
cout << getSentinel() << endl;
cout << "directed adjacency matrix: " << endl;
int graphmetrix[VERTEX_NUMBER][VERTEX_NUMBER] =
{
{0, 3, 8, 0x7fffffff, -4},
{0x7fffffff, 0, 0x7fffffff, 1, 7},
{0x7fffffff, 4, 0, 0x7fffffff, 0x7fffffff},
{2, 0x7fffffff, -5, 0, 0x7fffffff},
{0x7fffffff, 0x7fffffff, 0x7fffffff, 6, 0},
};
cout << "directed weight graph structure: " << endl;
for (int x = 0; x < VERTEX_NUMBER; ++ x)
{
cout << "vertex " << x + 1 << ";";
for (int y = 0; y < VERTEX_NUMBER; ++ y)
{
if (0 != graphmetrix[x][y])
{
cout << y + 1 << " ";
}
}
cout << endl;
}
cout << "origin: " << endl;
printfMatrix(graphmetrix);
Metrix c = floydWarshall(graphmetrix);
delete [] c;
return 0;
}
运行结果如下所示:
接着我们来看看它的详细结果图解:
比如,我们可以根据上图,在左边矩阵中一眼就可以看出1->2的的最短路径权重就是1,因为d[0][1] = 1。而在右边矩阵图中则可以看出1->2的最短路径权重的路径。首先是找II[0][1] = 3,可以看出2的前趋是3,然后找II[0][2] = 4,即3的前趋是4,依次可以找到4的前趋是5,5的前趋是1,则回到了起点1。则1->2的最短路径就是1->5->4->3->2。