Floyd Warshall与C中的负回路
我正在使用Floyd Warshalls算法进行图形搜索,不知道如何修改它以防止出现负循环 当我进入时:Floyd Warshall与C中的负回路,c,loops,graph,negative-number,floyd-warshall,C,Loops,Graph,Negative Number,Floyd Warshall,我正在使用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
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;}
我的距离矩阵在任何地方都有INF,没有成本
我遇到了一个更老的话题,修改后的算法是这样的:
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
然而,即使我使用这个补丁而不是我的函数,它仍然会循环并进一步降低成本。这个修正正确吗?如果没有,我应该如何重写它?谢谢。来自
因此,要使用Floyd–Warshall算法检测负循环,
可以检查路径矩阵的对角线,以及是否存在
负数表示图形至少包含一个
负循环[2]显然,在一个无向图中有一条负边
创建一个负循环,即涉及其事件的封闭行走
顶点
因此,如果d[k][k]小于0,您应该退出并说存在负循环。设置无效,您不能有负循环是的,工作正常。添加了此选项,而不是//修复负循环if*distanceMatrix[via][via]