简体   繁体   中英

Floyd's Shortest Path Algorithm C++

I have implemented a function for Floyd's algorithm in C++ for weighted digraphs that works correctly except that, when I generate a path matrix that gives the next node when trying to reach a destination, it puts the vertex immediately before the destination instead of the next node from the source in the matrix. The distance matrix (dist) comes out correctly, and if there is at most one node between the source and destination then the whole path matrix is correct. So if there are long shortest paths from vertex i to j, then path[i][j] should equal ak value connected to i but instead its ak value connected to j and I cannot figure out why. The function is shown below.

void floyd(const Graph<City>& g, double**& dist, int**& path)
{
    int n = g.size();
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            path[i][j]=0;
            if (i==j)
                dist[i][j]=0;
            else if (!g.isEdge(i, j))
                dist[i][j]=INFINITY;
            else
                dist[i][j]=g.retrieveEdge(i, j);
        }
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            for (int k = 1; k <= n; k++)
            {
                if ((dist[i][k]!=INFINITY) && (dist[k][j]!=INFINITY) && k!=i && k!=j && i!=j)
                {
                    if ((dist[i][j]) > (dist[i][k]+dist[k][j]))
                    {
                        path[i][j]=k;
                        dist[i][j]=dist[i][k]+dist[k][j];
                    }
                }
            }
        }
    }
}

So if there are long shortest paths from vertex i to j, then path[i][j] should equal ak value connected to i but instead its ak value connected to j and I cannot figure out why.

Unfortunately no to both. There is nothing in your implementation that guarantees that path[i][j] should equal a k value that comes immediately after i , and your observation that path[i][j] is currently a k value that comes immediately before j is also incorrect. (Please try a few more samples to verify the second point.)

The only thing that is guaranteed by your implementation is that the vertex path[i][j] == k lies somewhere in the shortest path from vertex i to vertex j .

Thus you can retrieve the path recursively by doing:

get_path(i, j):
    k = path[i][j]
    get_path(i, k) + k + get_path(k, j)

Having clarified that, there does exist a method where you can store path[i][j] such that it is the vertex that comes immediately after i .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM