我正在使用Floyd-Warshalls算法进行图搜索,不知道如何改变它来防止负循环。
当我进入时:
From Cost To
0 -1 1
1 -2 0我得到了成本矩阵:
0 1
0 -3 -4
1 -5 -10然后它开始循环,直到崩溃,因为它仍然增加了负边沿,进一步降低了成本。
void FloydWarshall(int ***distanceMatrix, int maxVertices)
{
int from, to, via;
for(from = 0; from < maxVertices; from++)
{
for(to = 0; to < maxVertices; to++)
{
for(via = 0; via < maxVertices; via++)
{
//Fix the negative looping
//EDIT FIX:
if((*distanceMatrix)[via][via]<0)
{fprintf(stderr, "Contains negative cycle!\n"); continue;}
//END EDIT
//Searches for the cheapest way from all-to-all nodes, if new path
// is cheaper than the previous one, its updated in matrix
(*distanceMatrix)[from][to] = min((*distanceMatrix)[from][to],
((*distanceMatrix)[from][via]+(*distanceMatrix)[via][to]));
}
}
}
}其中min是:
int min(int a,int b)
{return (a<b)? a:b;}而且我的distanceMatrix在任何免费的地方都有中转功能。
我遇到了更老的话题,修改后的算法是这样的:
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) // Go through all possible sources and targets
for(int k = 0; d[i][j] != -INF && k < n; k++)
if( d[i][k] != INF && // Is there any path from i to k?
d[k][j] != INF && // Is there any path from k to j?
d[k][k] < 0) // Is k part of a negative loop?
d[i][j] = -INF; // If all the above are true
// then the path from i to k is undefined然而,即使我使用这个修复而不是我的函数,它仍然循环并进一步降低了成本。这个修复正确吗?如果没有,我应该如何重写它?谢谢。
发布于 2013-05-15 05:21:20
来自wikipedia
因此,要使用弗洛伊德-沃肖尔算法检测负圈,可以检查路径矩阵的对角线,负数的存在表明图中至少包含一个负圈。2显然,在无向图中,负边创建了涉及其关联顶点的负圈(即闭合行走)。
所以,如果d[k][k]小于0,你应该直接退出,并说这是一个负循环。
https://stackoverflow.com/questions/16552916
复制相似问题