Shortest Path--floyd algorithm

Source: Internet
Author: User

First, the relevant introduction

Shortest path

    • The weight and the smallest path of the passing edge of a vertex that reaches another vertex.

Floyd algorithm

    • Extension of the Warshall algorithm
    • Three for loops to solve the problem
    • Time Complexity of O (N3)

Second, the algorithm introduction

Groundwork

Non-weighted graph G

Distance from Dis (AB) Node A to the shortest path of Node B

Auxiliary array path[] used to find the shortest path in the process of recording nodes

"Basic Ideas"

Problem: Choose a Node A from Figure g, and try to find the shortest path of a to Node B and dis (AB).

Analysis: The shortest path from Node A to Node B is only 2 possible:

    1. Straight from A to B
    2. From a through a number of nodes to B

Process: Starting from Node A, for each node adjacent to a x, we check whether the inequality dis (AX) + dis (XB) < dis (AB) is established?

    • If it is established that the path from a to x to B is shorter than a path directly to B , we set up dis (AB) = Dis (AX) + dis (XB), so that, while we traverse all possible node x, DIS ( AB) is constantly updated, and when all nodes X is traversed, the distance from the shortest path of A to B is recorded in Dis (AB).

It's easy, wait a minute, here's a snippet of code:

for (int i = 0; i < node number; ++i) {for (int j = 0; J < node number; ++j) {for (int k = 0; k < number of nodes; ++k) {if (Dis[i][k] + Dis[k][j] < Dis[i][j]) {//Find shorter path dis[i][j] = Dis[i][k] + dis[k][j];}}}}

Attention!! Here we have to pay attention to the loop nesting order , if the check all node x is placed in the most inner layer, then the result will be incorrect, why? Because of this, the shortest path of I to J is determined prematurely, and when there is a shorter path later, it is no longer updated .

Let's look at an example to see:

The red number in the figure represents the weight of the edge

If we check all node x in the inner layer , then for A->b, we can only find one path, that is a->b, the path distance is 9. And this is obviously not true, the real shortest path is a->d->c->b, and the path distance is 6.

The cause of the error is that we put the check all node x in the top layer, resulting in the early identification of A to B shortest path , when the shortest path to determine the a->b dis (AC) has not been calculated.

So, we need to rewrite the loop order as follows:

for (int k = 0; k < node number; ++k) {for (int i = 0; i < number of nodes; ++i) {for (int j = 0; J < number of nodes; ++j) {if (Dis[i][k] + Dis[k][j] < Dis[i][j]) {//Find shorter path dis[i][j] = Dis[i][k] + dis[k][j];}}}}

If you still do not understand, then use the draft paper to simulate again, then you will be enlightened. Half an hour is enough (it will save a lot of half an hour if you know).

Let's take another example to see the difference between the two:

① Cycle Order is i-j-k

If we now want to update the shortest distance of 1-4, to enumerate the number of cities, there are 0,1,2,3,4,5, if the shortest distance of 2-3 cities is 10, when passing the city for 2, found that 2-3 of the shortest distance of 10, may be larger than the other, Therefore, the minimum distance through 2 cities may be 8, the above 6 cases update found that 1-4 the shortest distance is 13.

When we continue to update, we update the minimum distance of 2-3 is 1, but we can no longer return to 1-4 this situation. Therefore, the shortest distance of 1-4 is obviously wrong.

② Cycle Order is k-i-j

When we update 1-4, 2-3 may not be updated, but 1-4 can be updated k times, even if not the shortest, later update to the time can be updated to the shortest. So this is the right way.

In summary, for each node x, we will continue to check the next node after all the I-j processing is complete .

"Find the Shortest Path"

    • Use of the path array: If the value of path (AB) is P, then the shortest path to node A to B is A->...->p->b

So, assuming we're looking for the shortest path to the a->b, then we'll look in turn, assuming that the value of path (AB) is P, then look for Path (AP), assuming that the value of Path (AP) is L, then look for Path (AL), assuming The value of path (AL) is a, the lookup ends , and the shortest path is a->l->p->b.

    • So, how do you populate the value of path?

Very simply, when we find that inequality dis (AX) + dis (XB) < dis (AB) is established, the shortest path is changed to A->...->x->...->b, and the value of path (XB) is known, So,path (AB) = Path (XB).

"Test Code"

#include <cstdio> #include <cmath> #include <cstring> #include <string> #include <iostream > #include <algorithm> #include <vector> #include <queue> #include <stack> #include <map > #include <set>using namespace std; #define INFINITE 1000//Max # # Max_vertex_count 20//maximum vertex number//////////// struct GRAPH{INTARRARCS[MAX_VERTEX_COUNT][MAX_ vertex_count];//adjacency matrix intnvertexcount;//number of vertices intnarccount;//edges};/////////////////////////////////////////////// void Readgraphdata (Graph *_pgraph) {std::cout << "Please enter the number of vertices and edges:"; Std::cin >> _ Pgraph->nvertexcount;std::cin >> _pgraph->narccount;std::cout << "Please enter adjacency matrix data:" << Std::endl; for (int row = 0, row < _pgraph->nvertexcount; ++row) {for (int col = 0; col < _pgraph->nvertexcount; ++col ) {std::cin >> _pgraph->arrarcs[row][col];}} void Floyd (int _arrdis[][max_vertex_count], int _arrpath[][max_vertex_count], int _nvertexcount) {//Initialize _arrpathfor first (int i = 0; i < _nvertexcount; ++i) {for (int j = 0; j < _nvertexcount; ++j) {_arrpath[i][j] = i;}} for (int k = 0; k < _nvertexcount; ++k) { for (int i = 0, i < _nvertexcount; ++i) {for (int j = 0; j < _nvertexcount; ++j) {if (_arrdis[i][k] + _arrdis[k][ J] < _arrdis[i][j]) {//Find shorter path _arrdis[i][j] = _arrdis[i][k] + _arrdis[k][j];_arrpath[i][j] = _arrpath[k][j];}}}} void Printresult (int _arrdis[][max_vertex_count], int _arrpath[][max_vertex_count], int _nvertexcount) {Std::cout < < "Origin-Destdistancepath" << std::endl;for (int i = 0; i < _nvertexcount; ++i) {for (int j = 0; J &L T _nvertexcount; ++J) {if (i! = j)//node is not itself {std::cout << i+1 << "," << j+1 << "\t\t"; if (INFINITE = = _arrd IS[I][J])//I-J does not exist path {std::cout << "INFINITE" << "\t\t";} Else{std::cout << _arrdis[i][j] << "\t\t";//Because we query the shortest path is from the back and forward, so we put the query node//pressed into the stack, the final popup in order to output results. std::stack<int> Stackvertices;int k = j;do {k = _arrpath[i][k];stackvertices.push (k);} while (k! = i);////////// Std::cout << stackvertices.top () +1; Stackvertices.pop (); unsigned int nlength = Stackvertices.size (); for (unsigned int nIndex = 0; NIndex < nlength; ++nind Ex) {std::cout << "," << Stackvertices.top () +1;stackvertices.pop ();} Std::cout << "," << j+1 << Std::endl;}}}} int main () {Graph mygraph;readgraphdata (&mygraph);/////////////////////////////////////////////////////////// int Arrdis[max_vertex_count][max_vertex_count];int arrpath[max_vertex_count][max_vertex_count];// First initialize arrdisfor (int i = 0; i < Mygraph.nvertexcount; ++i) {for (int j = 0; j < Mygraph.nvertexcount; ++j) {arrdis[i ][J] = Mygraph.arrarcs[i][j];}} Floyd (arrDis, Arrpath, mygraph.nvertexcount);////////////////////////////////////////////////////////////////////////// Printresult (Arrdis, Arrpath, mygraph.nvertexcount);///////////////////////////////////////////////////////////// return 0;}

Shortest Path--floyd algorithm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.