Shortest Path algorithm

Source: Internet
Author: User

Limited capacity, today just study two Fioyd and Dijkstra algorithm, there is a bellmanford to contact tomorrow, the next is C write the shortest path

Floyd algorithm

Part of the content reference http://leon.cc.blogbus.com/logs/3629782.html

Shortest path problem for All-pairs: Shortest path between all pairs of points

Dijkstra algorithm is to find the shortest path of the single source, if the figure is a bit of the shortest path, then there are the following two methods:

Solution One:

With each vertex in the graph as the source point, call the Dijkstra algorithm, the time complexity is O (N3);

Solution Two:

Floyd (Freud algorithm) is more concise, the algorithm complexity is still O (N3).

N
As mentioned in most textbooks, the shortest path of single source point without negative edge is used Dijkstra, and the shortest path of all points is Floyd. Indeed, we will use the Floyd algorithm, but not to say that Floyd is the best choice in all cases.

For those who have not learned Floyd, the first response to the problem of All-pairs shortest path after mastering Dijkstra may be: Calculate a bit of the single source point shortest path, you can get the shortest path of all points. A simple description of the algorithm is to execute n-times Dijkstra algorithm.

Floyd can be said to be an extension of the Warshall algorithm, three for loops can solve a complex problem, it should be said to be very classic. From its three-layer cycle, it can be seen that its complexity is N3, in addition to a second layer for the judgment can be slightly increased efficiency, there is little other way to reduce its complexity.

Comparing the two algorithms, it is not difficult to draw the following conclusions: For sparse graphs, the use of n times Dijkstra is excellent, for dense graphs, you can use the Floyd algorithm. In addition, the Floyd can handle graphs with negative edges.


The Floyd algorithm is described below:

The basic idea of Floyd algorithm:

The problem can be decomposed to find the shortest distance, and then consider how to find the corresponding road route. How to find the shortest path, here is still the knowledge of dynamic planning, for any city, I to J of the shortest distance is the existence of the k between I and J and do not go through K two possible, so you can make K=1,2,3,...,n (n is the number of cities), in the check D (IJ) and D (IK) + The value of D (KJ), in which D (IK) and D (KJ) are the shortest distances known so far between I and K and K to J, so that D (IK) +d (kj) is the shortest distance from I to J through K. So, if there is D (IJ) >d (ik) +d (kj), it means that the distance from I to go through K and J is shorter than the original I-J distance, naturally I to J D (IJ) is rewritten to D (IK) +d (kj), whenever a k is finished, d (IJ) is the current I to J shortest distance. Repeat this process, and finally, when all k is checked, the shortest distance between I and J is stored in D (IJ).

The basic steps of the Floyd algorithm are:

Define the NXN matrix sequence D-1, D0, ... Dn-1,

Initialization: D-1=c

The length of the d-1[i][j]= Edge <i,j>, which represents the initial shortest path length from I to J, i.e. it is the shortest path from the middle of I to J that does not pass through the other intermediate points.

Iteration: Set Dk-1 has been calculated, how to get DK (0≤k≤n-1)?

DK-1[I][J] indicates that the middle point from I to J is not greater than the shortest path of k-1 P:I...J,

Consider adding the vertex k to the path p to get the vertex sequence Q:I...K...J,

If q is not a path, the current shortest path is still the previous result: dk[i][j]= dk-1[i][j];

Otherwise, if the length of Q is less than the length of p, then q is substituted for p as the shortest path from I to J.

Since the two sub-paths of Q I...K and K...J are the shortest paths with intermediate points not greater than k-1, the shortest path length from I to j is not greater than K:

dk[i][j]=min{Dk-1[i][j], dk-1[i][k] +dk-1[k][j]}

Floyd algorithm implementation:
The problem can be fixed with three for loops, but there is one problem to be aware of, which is the nesting order of the FOR loop: we may be able to write such a program at hand, but if you think about it, you will find it problematic.
for (int i=0; i<n; i++)
for (int j=0; j<n; j + +)
for (int k=0; k<n; k++)

The problem is that we are too early to determine the distance of the i-k-j, assuming that once the shortest distance to find the i-p-j, I to J is quite finished, and will not change in the future, once I to j shorter distances can not be updated, so the result must be wrong. So you should write the program as follows:

for (int k=0; k<n; k++)
for (int i=0; i<n; i++)
for (int j=0; j<n; j + +)

The significance of this is to fix K, all I to J and the distance through K to find out, and then as mentioned in the beginning to compare and rewrite, because K is in the outermost, so will all the I to J are processed, will move to the next K, so there is no problem, it seems that the multi-layer cycle, We must be careful, otherwise it is easy to make a mistake.
The next step is to look at how to find the shortest path of the city, and here to use another matrix p, which is defined as: P (IJ) if the value of p, it means I to J of the shortest passing is i->...->p->j, That is to say, P is the last city before J in the shortest act of I to J. The initial value of the P-matrix is P (IJ) =i. With this matrix, it is easy to find the shortest path. For I to J to find P (IJ), so that p, I know the path i->...->p->j; again to find P (IP), if the value of Q,i to p the shortest path for i->...->q->p; to find P (IQ), if the value is R, I to q the shortest path is i->...->r->q; so repeatedly, to a certain p (it) value is I, the shortest path I to T is i->t, will be to the answer, I to J of the shortest act of i->t->...-> Q->p->j. Because the above algorithm is from the end point to the beginning of the order to find out, so the output of the time to turn it upside down.
However, how to dynamically backfill the values of P-matrices? Recall that when D (IJ) >d (ik) +d (kj), it is necessary to change the shortest path of I to J to go i->...->k->...->j this way, but the value of D (KJ) is known, in other words, k->...- >j This road is known, so k->...->j on this road J's last City (ie, p (KJ)) is also known, of course, because to change the path of I->...->k->...->j, J's previous city is just P ( KJ). So once D (IJ) >d (+d) (KJ) is found, p (KJ) is deposited in P (IJ).
The following is the specific C code:

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#define MAXSIZE 20

void Floyd (int [][maxsize], int [][maxsize], int);
void Display_path (int [][maxsize], int [][maxsize], int);
void reverse (int [], int);
void Readin (int [][maxsize], int *);

#define Maxsum (A, B) (((a)! = Int_max && (b)! = Int_max)?
((a) + (b)): Int_max)

void Floyd (int dist[][maxsize], int path[][maxsize], int n)
{
int I, j, K;
for (i = 0; i < n; i++)
for (j = 0; J < N; j + +)
PATH[I][J] = i;
for (k = 0; k < n; k++)
for (i = 0; i < n; i++)
for (j = 0; J < N; j + +)
if (Dist[i][j] > Maxsum (dist[i][k], dist[k][j]))
{
PATH[I][J] = Path[k][j];
DIST[I][J] = Maxsum (Dist[i][k], dist[k][j]);
}
}

void Display_path (int dist[][maxsize], int path[][maxsize], int n)
{
int *chain;
int count;
int I, j, K;
printf ("\n\norigin->dest Dist Path");
printf ("\ n-----------------------------");
Chain = (int *) malloc (sizeof (int) *n);
for (i = 0; i < n; i++)
for (j = 0; J < N; j + +)
{
if (i! = j)
{
printf ("\n%6d->%d", i+1, j+1);
if (dist[i][j] = = Int_max)
printf ("NA");
Else
{
printf ("%4d", Dist[i][j]);
Count = 0;
K = J;
Do
{
K = chain[count++] = Path[i][k];
} while (i! = k);
Reverse (chain, count);
printf ("%d", chain[0]+1);
for (k = 1; k < count; k++)
printf ("->%d", chain[k]+1);
printf ("->%d", j+1);
}
}
}
Free (chain);
}

#define SWAP (A, b) {temp = A; a = b; b = temp;}

void reverse (int x[], int n)
{
int I, j, temp;
for (i = 0, j = n-1; I < J; i++, j--)
SWAP (X[i], x[j]);
}

void Readin (int dist[][maxsize], int *number)
{
int origin, dest, length, n;
int I, J;
Char line[100];
Gets (line);
SSCANF (line, "%d", &n);
*number = n;
for (i = 0; i < n; i++)
{
for (j = 0; J < N; j + +)
DIST[I][J] = Int_max;
Dist[i][i] = 0;
}
Gets (line);
SSCANF (line, "%d%d%d", &origin, &dest, &length);
While (origin! = 0 && Dest! = 0 && Length! = 0)
{
DIST[ORIGIN-1][DEST-1] = length;
Gets (line);
SSCANF (line, "%d%d%d", &origin, &dest, &length);
}
}
The test program looks like this:
int main (void)
{
int dist[maxsize][maxsize];
int path[maxsize][maxsize];
int n;
printf ("\ninput The Path Information:");
printf ("\ n----------------------------\ n");
Readin (Dist, &n);
Floyd (Dist, path, n);
Display_path (dist, path, n);
GetChar ();
}
Where the Readin function specifies the format of the input, the first column indicates how many cities there are, and the second column is three digits after each row, the first and second are the start and end points of a path, the third number is the length of the path, and finally the input end condition is three 0. Here is an example of an input:
Input The path information:
--------------------------------------
4
1 2 5
2 1 50
2 3 15
2 4 5
3 1 30
3 4 15
4 1 15
4 3 5
0 0 0
The corresponding output results are:
Origin->dest Dist Path
----------------------------------------------
1->2 5 1->2
1->3 1->2->4->3
1->4 1->2->4
2->1 2->4->1
2->3 2->4->3
2->4 5 2->4
3->1 3->1
3->2 3->1->2
3->4 3->4
4->1 4->1
4->2 4->1->2
4->3 5 4->3

Dijkstra algorithm

A shortest path algorithm is used to calculate the shortest path of a node to all other nodes, and the Dijkstra algorithm is used in the dynamic routing protocol OSPF to calculate the shortest path for routing.

The algorithm itself is not in accordance with our normal thinking habits, we generally will, from the origin of all connected nodes, find the shortest path, and then from the shortest path that point to traverse all other points connected to it (except the origin), and so on. This can be done with a tree, but in most cases, this algorithm produces multiple paths, i.e. non-shortest paths.

The approximate process of the Dijkstra algorithm:

Suppose there are two sets or two tables, table A and table B.

Table A represents the build path, and Table B represents the last determined path

1. Starting from the origin, the Traverse examines all nodes connected to it, stores the origin and the nodes in table A, and records the cost between the two nodes.

2. Move the lowest-cost generation value and the two node to table B (where one is the origin).

3. Find the child nodes connected by this node and put them into table A to calculate the cost of the child nodes to the origin.

4. Repeat the second and third steps until table A is empty. The optimal tree is then calculated based on the data in table B.

There is another way of saying in Wikipedia that the input to the Dijkstra algorithm contains a power-heavy graph G, and a source vertex s in G. We use V to represent the collection of all vertices in G. Each edge in the graph is a pair of ordered elements formed by two vertices. (U,V) indicates that a path is connected from the vertex u to v. We have a collection of all sides of E, and the weights of the edges are defined by the weight function w:e→[0,∞]. Therefore, W (U,V) is the non-negative cost value from vertex u to vertex v. The cost of the edge can be imagined as a distance between two vertices. The cost value of any path between two points is the sum of the cost of all the edges on that path. It is known that V has the vertex s and the T,dijkstra algorithm can find the lowest cost path of S to T (i.e. shortest path). The algorithm can also find the shortest path from one vertex s to any other vertex in a diagram.

The underlying operation of the Dijstra algorithm is the expansion of the edge: if there is an edge from U to V, the shortest path from S to u can extend a path from S to V by adding an edge (u,v) to the tail. The length of this path is D[u]+w (u,v). If this value is smaller than the value currently known as D[v], we can replace the value in the current D[v] with the new value. An extended edge operation is performed until all D[v] represent the cost of the shortest path from S to v. The algorithm has been organized for

Dijkstra algorithm

The changes in the vertices and distances that you write for each update

Su

{1} {2,3,4,5,6} {0,2,4,∞,∞,∞}

{3,4,5,6} {0,2,3,6,4,∞}

{4,5,6} {0,2,3,6,4,∞}

{1,2,3,5} {4,6} {0,2,3,6,4,6}

{1,2,3,5,4} {6} {0,2,3,6,4,6}

{1,2,3,5,4,6} {} {0,2,3,6,4,6}

Shortest Path algorithm

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.