【问题标题】:Bug in my Floyd-Warshall C++ implementation我的 Floyd-Warshall C++ 实现中的错误
【发布时间】:2011-03-02 22:00:09
【问题描述】:

我的大学有一个任务,已经成功实施了 Dijkstra 和 Bellman-Ford,但我在这方面遇到了麻烦。一切看起来都很好,但它没有给我正确的答案。

代码如下:

void FloydWarshall()
{
    //Also assume that n is the number of vertices and edgeCost(i,i) = 0

    int path[500][500];

    /* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path
       from i to j using intermediate vertices (1..k−1).  Each path[i][j] is initialized to
       edgeCost(i,j) or infinity if there is no edge between i and j.
    */

    for(int i = 0 ; i <= nvertices ; i++)
        for(int j = 0 ; j <= nvertices ; j++)
            path[i][j] = INFINITY;

    for(int j = 0 ; j < narestas ; j++) //narestas = number of edges
    {
        path[arestas[j]->v1][arestas[j]->v2] = arestas[j]->peso; //peso = weight of the edge (aresta = edge)
        path[arestas[j]->v2][arestas[j]->v1] = arestas[j]->peso;
    }

    for(int i = 0 ; i <= nvertices ; i++) //path(i, i) = 0
        path[i][i] = 0;

    //test print, it's working fine
    //printf("\n\n\nResultado FloydWarshall:\n");
    //for(int i = 1 ; i <= nvertices ; i++)
    //    printf("distancia ao vertice %d:  %d\n", i, path[1][i]);


    // Here's the problem, it messes up, and even a edge who costs 4, and the minimum is 4, it prints 2.

    //for k = 1 to n
    for(int k = 1 ; k <= nvertices ; k++)
       //for i = 1 to n
       for(int i = 1 ; i <= nvertices ; i++)
           //for j := 1 to n
           for(int j = 1 ; j <= nvertices ; j++)
               if(path[i][j] > path[i][k] + path[k][j])
                   path[i][j] = path[i][k] + path[k][j];


    printf("\n\n\nResultado FloydWarshall:\n");
    for(int i = 1 ; i <= nvertices ; i++)
        printf("distancia ao vertice %d:  %d\n", i, path[1][i]);
}

我正在使用我制作的这个图表示例:

6 7

1 2 4
1 5 1
2 3 1
2 5 2
5 6 3
6 4 6
3 4 2

意味着我们有 6 个顶点(1 到 6)和 7 个边(1,2),权重为 4...等等。

如果有人需要更多信息,我愿意提供,只是厌倦了查看此代码并没有发现错误。

【问题讨论】:

    标签: c++ graph floyd-warshall


    【解决方案1】:

    另外,你的迭代的开始和结束不是在几个地方相差一个吗?您可能希望它们从 0 运行到 nvertices-1;即for (int i = 0; i &lt; nvertices; i++)。

    【讨论】:

      【解决方案2】:

      没关系,我休息一下吃点东西发现了错误。

      无穷大被定义为INT_MAX,所以一旦你向它添加一些东西,它就会变成负数。

      我只定义了一些大的东西(对于我的问题,比如超过 9000,没有图形路径会占用更多),它工作正常。

      但我可以知道你为什么建议尹吗?我没听懂。

      谢谢

      【讨论】:

        【解决方案3】:
         if(path[i][j] > path[i][k] + path[k][j])
          path[i][j] = path[i][k] + path[k][j];
        

        在这里做一些检查。例如如果 path[i][k] 和 path[k][j] 是非无限的,并且 i!=j i!=k 和 k!=j。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-11-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-01
          • 2016-07-28
          • 1970-01-01
          相关资源
          最近更新 更多