Find all the shortest paths and distances with Floyd-Warshall

Firstly, a little background: I'm working on creating a simple graph class with basic graph algorithms (Dijkstra, Floyd-Warshall, Bellman-Ford, etc.) for use as a reference sheet for the upcoming programming contest.

So far I have a valid version of Floyd-Warshall, but the disadvantage is that so far it has given me the shortest distance between two nodes, and not the shortest path. Preferably, I would like to build the route inside the algorithm itself, instead of calling another function to restore it.

Here is some information about the data structures that I use:

vector< vector<int> > graph //contains the distance values from each node to each other node (graph[1][3] contains the length of the edge from node #1 to node #3, if no edge, the value is INF

vector< vector<int> > path //contains the "stepping stones" on how to reach a given node. path[st_node][end_node] contains the value of the next node on the way from end_node -> st_node

Here is an example of the graph data I am using:

INF 10  INF INF INF INF
INF INF 90  15  INF INF
INF INF INF INF INF 20
INF INF INF INF 20  INF
INF INF  5  INF INF INF
INF INF INF INF INF INF

"" ( Dijkstra ):

INF  0   4   1   3   2
INF INF  4   1   3   2
INF INF INF INF INF  2
INF INF  4  INF  3   2
INF INF  4  INF INF  2
INF INF INF INF INF INF

, : ( PasteBin).

!

: :

INF INF  4   1   3   4
INF INF  4  INF  3   4
INF INF INF INF INF INF
INF INF  4  INF INF  4
INF INF INF INF INF  2
INF INF INF INF INF INF

, , "" . , node 0 node 1 undefined. (, , Nali4Freedom )

+5
2

!

, :

// Time to clean up the path graph...
for (int st_node = 0; st_node < this->size; st_node++)
{
    for (int end_node = 0; end_node < this->size; end_node++)
    {
        int mid_node = this->path[st_node][end_node];

        if (mid_node == INF)
        {
            // There is no mid_node, it probably just a single step.
            if (this->graph[st_node][end_node] != INF)
            {
                this->path[st_node][end_node] = st_node;
            }

        } else {
            // The mid_node may be part of a multi-step, find where it leads.
            while (this->path[mid_node][end_node] != INF)
            {
                if (this->path[mid_node][end_node] == mid_node) { break; }  // Infinite loop
                if (this->path[mid_node][end_node] == INF) { break; }   // Dead end

                mid_node = this->path[mid_node][end_node];
            }

            this->path[st_node][end_node] = mid_node;

        }   // IF mid_node
    }   // FOR end_node
}   // FOR st_node

, node A node B - (mid_node == INF) , . , node , node (this->path[mid_node][end_node] != INF), , , .

, , , -, !

+2

. | V | x | V | 'next', i, j , , node node j. j [i] [j] [i] [j] j. , , .

+1

All Articles