【Data Structure Learning Record 23】——The shortest path

I. Overview

The shortest path means: if a directed and undirected net is given, find a path that minimizes the weight sum between two vertices.
For example: In
Insert picture description here
this figure, the shortest path from V 0 to V 5 is 60. (V 0 -V 4 -V 3 -V 5 )

2. Dijkstra algorithm

This algorithm is exactly the same as the previous minimum spanning tree algorithm. The code is basically the same, but the object is different. We have to add an array to store the shortest path distance value. If you want a specific path, you have to open an array to save the intermediate variables.
This code is not written in detail, you can look at other codes.

Three. Floyd (Floyd) algorithm

How to put it, this is a kind 动态规划of thinking, because there were contact rules before, so it is easy to understand. As long as we write our transfer equation, we can implement the code.
Freud’s core idea is: the 如果dis(A,B) + dis(B,C) < dis(A,C),则dis(A,C)=dis(A,B) + dis(B,C)
state transition equation is: dk (i, j) = min (dk − 1 (i, j), dk − 1 (i, k) + dk − 1 (k, j)) d^k(i,j)=min(d^{k-1}(i,j),d^{k-1}(i,k)+d^{k-1}(k,j))dk(i,j)=m i n ( dk1(i,j),dk1(i,k)+dk1(k,j ) ) is
equivalent to an intermediate point. If the distance between the two points becomes smaller through the intermediate point, then the distance between the two points is updated. The idea of ​​moving rules is very clever and much more understandable.
So, we can complete three cycles:

  1. The first level of loop: traverse all points as an intermediate point. (Traverse k)
  2. The second loop: traverse all the starting points. (Traverse i)
  3. The third loop: traverse all end points. (Traverse k)
    So the code is here:
//k为中间点 
for(k = 0; k < G.vexnum; k++)
{
    
    
    //v为起点 
    for(i = 0 ; i < G.vexnum; i++)
    {
    
    
        //w为终点 
        for(j =0; j < G.vexnum; j++)
        {
    
    
            if(D[i][j] > (D[i][k] + D[k][j]))
            {
    
    
                D[i][j] = D[i][k] + D[k][j];
                //更新最小路径 
            }
        }
    }
}

Finally, the leading matrix D is the value of the shortest path between any two points.
If you want a path, open an array and update the path at the innermost level.

Four. Postscript

I feel that this article is well written, but it is my notes after all, so I can make trouble if I understand it. . . .

Guess you like

Origin blog.csdn.net/u011017694/article/details/111151735