Error in my implementation of Floyd-Warshall C ++

I have a task for my college, Dijkstra and Bellman Ford have already been successfully implemented, but I have problems with this. Everything looks good, but it does not give me the correct answer.

Here is the code:

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 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 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]);
}

I use this graph example that I made:

6 7

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

means that we have 6 vertices (from 1 to 6) and 7 edges (1,2) with a weight of 4 ... etc.

If someone needs more information, I have to give it, I'm just tired of looking at this code and not finding an error.

+3
source share
3 answers

Nevermind, I took a break to eat something and found a mistake.

Infinity is defined as INT_MAX, so as soon as you add something to it, it becomes negative.

- ( , , over9000, ), .

, ? .

+2
 if(path[i][j] > path[i][k] + path[k][j])
  path[i][j] = path[i][k] + path[k][j];

. [i] [k] [k] [j] , != j != k k!= j.

0

Also, aren't the start and end ends of your iteration along the way one of several places? You probably want them to work from 0 to nvertices-1; those. for (int i = 0; i < nvertices; i++).

0
source

Source: https://habr.com/ru/post/1749696/


All Articles