The shortest path and the minimum spanning tree are very different in application, such as: the first construction of a subway, and then a number of points on the subway, the need to build a shortest distance subway line, these subway points connected together, this is the minimum spanning tree (the distance between the point and point is known). Xiao Qiang needs to travel from point A to point B, the middle will pass several points, need to find a shortest path to reach point B. It is obvious from the application that the purpose of the two is different and the initialization condition is different.
First, Dijkstra (Dijkstra) algorithm
The Dijkstra (Dijkstra) algorithm is a typical shortest path routing algorithm used to calculate the shortest path of a node to all other nodes. The main feature is to extend from the center of the starting point to the outer layer until it expands to the end point.
1. Algorithm idea
Make G = (v,e) A weighted graph, the vertex set V in the graph is divided into two groups, the first set is the shortest path of the vertex set S (the initial s only the source node, each subsequent to find a shortest path, the corresponding vertex is added to the set S, until all the vertices are added to the s) The second group is the vertex set of the indeterminate shortest path U. During the join process, the shortest path length that is always maintained from the source node V to the vertices in S is less than the shortest path length from the source node V to any vertex in U.
For the two sets established, after the Dijkstra algorithm is run, two of the elements in the set are 1,2,3,4,5,6 in the array abcdef coordinates:
Iteration |
S |
U |
DIST[2] |
DIST[3] |
DIST[4] |
DIST[5] |
DIST[6] |
1 |
A |
- |
6 |
3 |
MAX |
MAX |
MAX |
2 |
A,c |
C |
5 |
3 |
6 |
7 |
MAX |
3 |
A,c,b |
B |
5 |
3 |
6 |
7 |
MAX |
4 |
A,c,b,d |
D |
5 |
3 |
6 |
7 |
9 |
5 |
A,c,b,d,e |
E |
5 |
3 |
6 |
7 |
9 |
6 |
A,b,c,d,e,f |
F |
5 |
3 |
6 |
7 |
9 |
2. Algorithm analysis
Based on the above analysis, you learn that you need to create two arrays, create a collection of vertices, and a collection of edges to hold the weights of the points to each edge, then select the vertices of the smallest weighted edge pairs in the weights collection, and then continue the loop.
- Create vertices in conjunction with Nnodeindex, initialized to 0, and 1 in the array, indicating that the corresponding vertices have been added to the shortest path vertex collection s.
- Creates an edge collection of the initial vertex to each vertex, holds the distance (weight) of the vertex to each vertex, and initializes the row element in the adjacency matrix (similar to the minimum spanning tree).
- The loop calculates the minimum value of this vertex to each vertex, learns that after nnodeindex[i] = 1, and updates the value of the Edge collection.
- Generally speaking, it's relatively easy.
3. Example Diagram explanation
4. Code
//Dijkstra AlgorithmvoidGraphdata::shortpath_dijkstra (Grapharray *Parray) { //The Dijkstra algorithm and the minimum spanning tree algorithm are similar in some way intmin,i,j,k; intNnodeindex[maxvex];//To save the associated vertex coordinates, 1 is the over-node that has traversed the access (in the smallest spanning tree, a numeric representation that iterates through the same value and coordinates is an edge) . intNnodeweight[maxvex];//holds the weight of a vertex to each vertex, not for the 0 and maximum values. intNpathlength[maxvex];//coordinates and elements are represented as simultaneous values and coordinate representations on one side, and primes have the same//Two initialization of an arrayprintf"start initialization, the weights for the current vertex edge are:"); for(i =0; i<parray->numvertexes;i++) {Nnodeindex[i]=0; Nnodeweight[i]= parray->arg[0][i];//sets the first vertex in the matrix as the initial point. Npathlength[i] =0; printf ("%c", Nnodeweight[i]); } nnodeweight[0] =0;//Select the coordinate point 0 as the starting point. nnodeindex[0] =1;//so 0 is the starting point, set to 1. (different from Prime)//Algorithmic Thinking for(i =1;i< parray->numvertexes;i++) {min= INFINITY;//the initial weight value is the maximum value;j =1; K=0; //loop through all vertices, looking for vertices with the lowest weight at the initial point, write down the weights and coordinates while(J < Parray->numvertexes) { //If the weight value is not 0, and the weight is less than min, 0 represents itself if(!nnodeindex[j]&&nnodeweight[j] < min)//here the prime is not 0 in weight,{min=Nnodeweight[j]; K= J;//Save the coordinate values of the above vertices} J++; } printf ("current vertex edge middle weight minimum edge (%d,%d) \ n", Nnodeindex[k], k);//lowest weight in print current vertex edge//Nnodeweight[k] = 0;//sets the weight of the current vertex to 0, indicating that the vertex has completed the taskNNODEINDEX[K] =1;//Place the nearest vertex currently found at 1//For (j = 1;j< parray->numvertexes;j++)//loop all vertices to find the smallest edge with the K vertex//{ // //if the value of the vertex with the subscript k is less than the spanning tree weights that were not previously added to these vertices//if (nnodeweight[j]! = 0&&parray->arg[k][j] < Nnodeweight[j])// { //Nnodeweight[j] = parray->arg[k][j]; //nnodeindex[j] = k; //Deposit the vertex labeled K in Adjvex// } //} //fixed current shortest path and distance for(j =1;j< parray->numvertexes;j++)//loop all vertices to find the smallest edge with the K vertex { //if the value of the vertex with the subscript k is less than the spanning tree weights that were not previously added to these vertices if(!nnodeindex[j] && parray->arg[k][j] + min<Nnodeweight[j]) {Nnodeweight[j]= Parray->arg[k][j] +min; NPATHLENGTH[J]= k;//Deposit the vertex labeled K in Adjvex } } //Print current vertex statusprintf"The coordinate points group is:"); for(j =0;j< parray->numvertexes;j++) {printf ("%3d", Npathlength[j]); } printf ("\ n"); printf ("The weights array is:"); for(j =0;j< parray->numvertexes;j++) {printf ("%3d", Nnodeweight[j]); } printf ("\ n"); }}
5. Code Analysis
is the adjacency matrix of the graph, corresponding to the above example diagram analysis, we analyze the results of the code operation.
Is the result of the code operation, first the first time, the minimum edge is (0,2), the added vertex is C. The second smallest edge is (0,1), and the result of the join IS B. And so on, you will find that the result is the same as the previous example diagram analysis.
The last weighted array (0,5,3,6,7,9) means that the distance from vertex A to b,c,d,e,f is 5,3,6,7,9. A->b:5, based on the coordinate points group npathlength[1] = 2, means that after the vertex c with coordinates 2, see npathlength[2] = 0, end. Again such as a->d:6,npathlength[4] = 2, so for a->c->d. The same goes for other ways.
Second, Floyd algorithm
The Dijkstra algorithm solves the problem of the shortest distance from one source point to the remaining individual vertices. Judging from the cyclic statement, the time complexity of the algorithm is O (N2). Adding a loop to the outside of the loop also becomes the shortest distance for all vertices. The complexity of this algorithm is O (N3).
Freud (Floyd) algorithm is an O (n) event complexity algorithm, but the algorithm is very concise and elegant.
1. Algorithm idea
The Floyd algorithm is a classical dynamic programming algorithm. In plain language, the first goal is to find the shortest path from point I to J. From the point of view of dynamic planning, we need to make a reinterpretation of this goal (this interpretation is the essence of dynamic planning the most creative).
The shortest path from any node I to any node J is 2 possible, and 1 is straight from I to j,2 from I through several nodes K to J. Therefore, we assume that dis (i,j) is the distance from the shortest path of node u to node V, for each node K, we check whether dis (i,k) + dis (k,j) < dis (I,J) is established, if it is established, prove that the path from I to K to J is shorter than I direct to J Path, We set up dis (i,j) = Dis (i,k) + dis (k,j) so that when we traverse through all nodes K,dis (i,j) The distance from the shortest path of I to J is recorded.
2. Algorithm analysis
- Creates a matrix that records the weights of two vertices. In the Dijkstra algorithm, the path length of a vertex to another vertex is recorded, an array is declared, where each vertex is, so it is a matrix.
- Create a matrix that records the path of a vertex to another vertex, which is explained later.
- Floyd algorithm idea: For each pair of vertices u and V, see if there is a vertex w so that the path from u to W to V is shorter than known. The weights Shenning updated, as well as the path matrix.
3. Example Diagram explanation
(1) The program begins to run, and the 第4-11 line is initialized with D and P, making them the two matrices. Also obtained from The matrix, the V0->V1 path weight is the 1,v0->v2 path weight of 5,v0->v3 infinity line, so the path weight value is the maximum value of 65535.
(2) the 12th to 25th Line, is the main loop of the algorithm, a total of three layers of nesting, K represents the transfer vertex subscript. V represents the starting vertex, and W represents the end vertex.
(3) When k = 0 o'clock, that is, all the vertices are v0 transit, calculate whether there is a change in the shortest path. Unfortunately the result is that there is no change as shown in.
(4) When k = 1 o'clock, that is, all the vertices are V1 transit. At this point, when v = 0 o'clock, originally d[0][2] = 5, now due to d[0][1] + d[1][2] = 4. Therefore, by the 20th line of code, the two take its minimum value, get d[0][2] = 4, the same can get d[0][3] = 8, d[0][4] = 6, when V = 2, 3, 4 o'clock, also modified some data, see the left side of the dotted box data. Due to the correction of these minimum weights, the path matrix P is also processed and changed to the current P[v][k] value, as shown in line 21st of the code.
(5) Next is k = 2, until the end of 8, indicating that each vertex to do the calculation results of the transfer, of course, we also need to be clear, D0 is based on D-1, D1 is based on D0, ..., D8 is based on D7. Finally, when k = 8 o'clock, two matrix data is shown.
At this point, our shortest path is complete. You can see that the value of the V0 line of the matrix is exactly the same as the value of the D array evaluated by the Dijkstra algorithm. And here is the shortest path weights for all vertices to all vertices and can be computed.
So how to get the specific shortest path from the P-path array? Take V0 to V8 for example, from the right of the V8 column, p[0][8]= 1, get to go through the vertex v1, and then replace 1 0, get p[1][8] = 2, the description to go through v2, then 2 instead of 1 get p[2][8] = 4, the description to go through V4, then 4 to replace 2, get p[4][8]= 3, the explanation to go through 3, ..., it is easy to pull down the final shortest path value of V0->V1->V2->V4->V3->V6->V7->V8.
4. Sample Code
//Floyd algorithmvoidGraphdata::shortpath_floyd (Grapharray *Parray) { inti,j,m,k; intNnodeindex[maxvex][maxvex]; intNnodeweight[maxvex][maxvex]; for(i =0;i< parray->numvertexes;i++) { for(j =0;j< parray->numvertexes;j++) {Nnodeindex[i][j]= J;/*Initialize*/Nnodeweight[i][j]= parray->arg[i][j];/*[I][j] value is the weighted value between the corresponding points*/ } } for(i =0;i< parray->numvertexes;i++) { for(j =0;j< parray->numvertexes;j++) { for(k =0; k<parray->numvertexes;k++) { if(Parray->arg[j][k] > parray->arg[j][i] + parray->Arg[i][k]) { /*shorter paths than the original two-point path if you pass the subscript as a K-vertex path*/Nnodeweight[j][k]= Parray->arg[j][i] + parray->arg[i][k];/*Sets the current two-point weighted value to a smaller one*/Nnodeindex[j][k]= Nnodeindex[j][i];/*path is set to the vertex labeled K*/ } } } } for(i =0; i< parray->numvertexes;i++) { for(j =0;j< parray->numvertexes;j++) {printf ("v%d-v%d Weight:%d", I,j,nnodeweight[i][j]); M= Nnodeindex[i][j];//gets the vertex subscript of the first path pointprintf"Path:%d", i);//Print Source Point while(m!=j) {printf ("- %d", m);//Print path verticesm = Nnodeindex[m][j];//gets the next path vertex subscript} printf ("%d\n", m);//Prints the end of the path. } printf ("\ n"); }}
5. Code Analysis
Also for the Dijkstra algorithm, the same adjacency matrix, we finally found that the v0 to the individual vertex data and the data in the Dijkstra, and also show the path through the vertex.
Brief discussion on data structure-shortest path