1

我正在使用 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 有 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

但是,即使我使用此修复程序而不是我的函数,它仍然会循环并进一步降低成本。这个修复正确吗?如果没有,我应该如何重写它?谢谢。

4

1 回答 1

0

来自维基百科

因此,要使用 Floyd-Warshall 算法检测负循环,可以检查路径矩阵的对角线,负数的存在表明该图至少包含一个负循环。 [2] 显然,在无向图中,负边会创建一个涉及其入射顶点的负循环(即封闭游走)。

因此,如果d[k][k]永远小于0您应该退出并说存在负循环。

于 2013-05-14T21:21:19.650 回答