程序员的算法课(19)-常用的图算法:最短路径(Shortest Path)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_37609579/article/details/100110115

一、最短路径问题

【google笔试题】一个环形公路,给出相邻两点的距离(一个数组),求任意两点的最短距离,要求空间复杂度不超过O(N)。

如果从有向图中某一顶点(称为源点)到达另一顶点(称为终点)的路径可能不止一条,如何找到一条路径使得沿此路径上各边上的权值总和达到最小。

最短路径问题是图论研究中的一个经典算法问题,旨在寻找图(由结点和路径组成的)中两结点之间的最短路径。算法具体的形式包括:

  1. 确定起点的最短路径问题- 即已知起始结点,求最短路径的问题。适合使用Dijkstra算法。
  2. 确定终点的最短路径问题- 与确定起点的问题相反,该问题是已知终结结点,求最短路径的问题。在无向图中该问题与确定起点的问题完全等同,在有向图中该问题等同于把所有路径方向反转的确定起点的问题。
  3. 确定起点终点的最短路径问题- 即已知起点和终点,求两结点之间的最短路径。
  4. 全局最短路径问题- 求图中所有的最短路径。适合使用Floyd-Warshall算法 。

解决最短路的问题有以下算法,Dijkstra算法,Bellman-Ford算法,Floyd算法和SPFA算法等。

二、邻接矩阵和邻接表的比较?

图的存储结构主要分两种,一种是邻接矩阵,一种是邻接表。

图的邻接矩阵存储方式是用两个数组来表示图。一个一维数组存储图中顶点信息,一个二维数组(邻接矩阵)存储图中的边或弧的信息。

è¿éåå¾çæè¿°

邻接表是数组与链表相结合的存储方法。

è¿éåå¾çæè¿°

对于带权值的网图,可以在边表结点定义中再增加一个weight的数据域,存储权值信息即可。如下图所示。

è¿éåå¾çæè¿°

邻接表的处理方法是这样的:

  • 图中顶点用一个一维数组存储,当然,顶点也可以用单链表来存储,不过,数组可以较容易的读取顶点的信息,更加方便。
  • 图中每个顶点vi的所有邻接点构成一个线性表,由于邻接点的个数不定,所以,用单链表存储,无向图称为顶点vi的边表,有向图则称为顶点vi作为弧尾的出边表。

三、Dijkstra(迪杰斯特拉)算法-解决单源最短路径

1.定义

Dijkstra(迪杰斯特拉)算法是典型的单源最短路径算法,用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。Dijkstra算法是很有代表性的最短路径算法,在很多专业课程中都作为基本内容有详细的介绍,如数据结构,图论,运筹学等等。举例来说,如果图中的顶点表示城市,而边上的权重表示著城市间开车行经的距离,该算法可以用来找到两个城市之间的最短路径。

2.基本思想

每次找到离源点(如1号结点)最近的一个顶点,然后以该顶点为中心进行扩展,最终得到源点到其余所有点的最短路径。

3.基本步骤

  • 设置标记数组book[]:将所有的顶点分为两部分,已知最短路径的顶点集合P和未知最短路径的顶点集合Q,很显然最开始集合P只有源点一个顶点。book[i]为1表示在集合P中;
  • 设置最短路径数组dst[]并不断更新:初始状态下,令dst[i] = edge[s][i](s为源点,edge为邻接矩阵),很显然此时dst[s]=0,book[s]=1。此时,在集合Q中可选择一个离源点s最近的顶点u加入到P中。并依据以u为新的中心点,对每一条边进行松弛操作(松弛是指由结点s-->j的途中可以经过点u,并令dst[j]=min{dst[j], dst[u]+edge[u][j]}),并令book[u]=1;
  • 在集合Q中再次选择一个离源点s最近的顶点v加入到P中。并依据v为新的中心点,对每一条边进行松弛操作(即dst[j]=min{dst[j], dst[v]+edge[v][j]}),并令book[v]=1;
  • 重复3,直至集合Q为空。

4.图示

5.代码

代码来自于书《Data Structure & Algorithm in JAVA》

 
  1.  
    // path.java
  2.  
    // demonstrates shortest path with weighted, directed graphs
  3.  
    // to run this program: C>java PathApp
  4.  
    ////////////////////////////////////////////////////////////////
  5.  
    class DistPar // distance and parent
  6.  
    { // items stored in sPath array
  7.  
    public int distance; // distance from start to this vertex
  8.  
    public int parentVert; // current parent of this vertex
  9.  
     
  10.  
    // -------------------------------------------------------------
  11.  
    public DistPar(int pv, int d) // constructor
  12.  
    {
  13.  
    distance = d;
  14.  
    parentVert = pv;
  15.  
    }
  16.  
    // -------------------------------------------------------------
  17.  
    } // end class DistPar
  18.  
     
  19.  
    ///////////////////////////////////////////////////////////////
  20.  
    class Vertex {
  21.  
    public char label; // label (e.g. 'A')
  22.  
    public boolean isInTree;
  23.  
     
  24.  
    // -------------------------------------------------------------
  25.  
    public Vertex(char lab) // constructor
  26.  
    {
  27.  
    label = lab;
  28.  
    isInTree = false;
  29.  
    }
  30.  
    // -------------------------------------------------------------
  31.  
    } // end class Vertex
  32.  
     
  33.  
    ////////////////////////////////////////////////////////////////
  34.  
    class Graph {
  35.  
    private final int MAX_VERTS = 20;
  36.  
    private final int INFINITY = 1000000;
  37.  
    private Vertex vertexList[]; // list of vertices
  38.  
    private int adjMat[][]; // adjacency matrix
  39.  
    private int nVerts; // current number of vertices
  40.  
    private int nTree; // number of verts in tree
  41.  
    private DistPar sPath[]; // array for shortest-path data
  42.  
    private int currentVert; // current vertex
  43.  
    private int startToCurrent; // distance to currentVert
  44.  
     
  45.  
    // -------------------------------------------------------------
  46.  
    public Graph() // constructor
  47.  
    {
  48.  
    vertexList = new Vertex[MAX_VERTS];
  49.  
    // adjacency matrix
  50.  
    adjMat = new int[MAX_VERTS][MAX_VERTS];
  51.  
    nVerts = 0;
  52.  
    nTree = 0;
  53.  
    for (int j = 0; j < MAX_VERTS; j++) // set adjacency
  54.  
    for (int k = 0; k < MAX_VERTS; k++) // matrix
  55.  
    adjMat[j][k] = INFINITY; // to infinity
  56.  
    sPath = new DistPar[MAX_VERTS]; // shortest paths
  57.  
    } // end constructor
  58.  
     
  59.  
    // -------------------------------------------------------------
  60.  
    public void addVertex(char lab) {
  61.  
    vertexList[nVerts++] = new Vertex(lab);
  62.  
    }
  63.  
     
  64.  
    // -------------------------------------------------------------
  65.  
    public void addEdge(int start, int end, int weight) {
  66.  
    adjMat[start][end] = weight; // (directed)
  67.  
    }
  68.  
     
  69.  
    // -------------------------------------------------------------
  70.  
    // find all shortest paths
  71.  
    public void path() {
  72.  
    //step1 initial
  73.  
    int startTree = 0; // start at vertex 0
  74.  
    vertexList[startTree].isInTree = true; //isInTree records whether the vertex's visited
  75.  
    nTree = 1; //record how many vertices has been visited
  76.  
     
  77.  
    // transfer row of distances from adjMat to sPath
  78.  
    for (int j = 0; j < nVerts; j++) {
  79.  
    int tempDist = adjMat[startTree][j];
  80.  
    sPath[j] = new DistPar(startTree, tempDist); //sPath is the note, here represent as an array
  81.  
    }
  82.  
     
  83.  
    while (nTree < nVerts) { //base case: until all vertices are in the tree
  84.  
    //step2 get minimum from sPath
  85.  
    int indexMin = getMin();
  86.  
    int minDist = sPath[indexMin].distance;
  87.  
     
  88.  
    //special case: if all infinite or in tree,sPath is complete
  89.  
    if (minDist == INFINITY) {
  90.  
    System.out.println("There are unreachable vertices");
  91.  
    break;
  92.  
    } else { // reset currentVert
  93.  
    currentVert = indexMin; // to closest vert
  94.  
    // minimum distance from startTree is to currentVert, and is startToCurrent
  95.  
    startToCurrent = sPath[indexMin].distance;
  96.  
    }
  97.  
    // put current vertex in tree
  98.  
    vertexList[currentVert].isInTree = true;
  99.  
    nTree++;
  100.  
     
  101.  
    //step3 update path
  102.  
    updatePath(); // update sPath[] array
  103.  
    } // end while(nTree<nVerts)
  104.  
     
  105.  
    //step4 printout all shortest path
  106.  
    displayPaths(); // display sPath[] contents
  107.  
     
  108.  
    nTree = 0; // clear tree
  109.  
    for (int j = 0; j < nVerts; j++)
  110.  
    vertexList[j].isInTree = false;
  111.  
    } // end path()
  112.  
     
  113.  
    // -------------------------------------------------------------
  114.  
    public int getMin() // get entry from sPath
  115.  
    { // with minimum distance
  116.  
    int minDist = INFINITY; // assume minimum
  117.  
    int indexMin = 0;
  118.  
    for (int j = 1; j < nVerts; j++) // for each vertex,
  119.  
    { // if it's in tree and
  120.  
    if (!vertexList[j].isInTree && // smaller than old one
  121.  
    sPath[j].distance < minDist) {
  122.  
    minDist = sPath[j].distance;
  123.  
    indexMin = j; // update minimum
  124.  
    }
  125.  
    } // end for
  126.  
    return indexMin; // return index of minimum
  127.  
    } // end getMin()
  128.  
     
  129.  
    // -------------------------------------------------------------
  130.  
    public void updatePath() {
  131.  
    // adjust values in shortest-path array sPath
  132.  
    int column = 1; // skip starting vertex
  133.  
    while (column < nVerts) // go across columns
  134.  
    {
  135.  
    // if this column's vertex already in tree, skip it
  136.  
    if (vertexList[column].isInTree) {
  137.  
    column++;
  138.  
    continue;
  139.  
    }
  140.  
    // calculate distance for one sPath entry
  141.  
    // get edge from currentVert to column
  142.  
    int currentToFringe = adjMat[currentVert][column];
  143.  
    // add distance from start
  144.  
    int startToFringe = startToCurrent + currentToFringe;
  145.  
    // get distance of current sPath entry
  146.  
    int sPathDist = sPath[column].distance;
  147.  
     
  148.  
    // compare distance from start with sPath entry
  149.  
    if (startToFringe < sPathDist) // if shorter,
  150.  
    { // update sPath
  151.  
    sPath[column].parentVert = currentVert;
  152.  
    sPath[column].distance = startToFringe;
  153.  
    }
  154.  
    column++;
  155.  
    } // end while(column < nVerts)
  156.  
    } // end adjust_sPath()
  157.  
     
  158.  
    // -------------------------------------------------------------
  159.  
    public void displayPaths() {
  160.  
    for (int j = 0; j < nVerts; j++) // display contents of sPath[]
  161.  
    {
  162.  
    System.out.print(vertexList[j].label + "="); // B=
  163.  
    if (sPath[j].distance == INFINITY)
  164.  
    System.out.print("inf"); // inf
  165.  
    else
  166.  
    System.out.print(sPath[j].distance); // 50
  167.  
    char parent = vertexList[sPath[j].parentVert].label;
  168.  
    System.out.print("(" + parent + ") "); // (A)
  169.  
    }
  170.  
    System.out.println("");
  171.  
    }
  172.  
    // -------------------------------------------------------------
  173.  
    } // end class Graph
  174.  
     
  175.  
    ////////////////////////////////////////////////////////////////
  176.  
    class PathApp {
  177.  
    public static void main(String[] args) {
  178.  
    Graph theGraph = new Graph();
  179.  
    theGraph.addVertex('A'); // 0 (start)
  180.  
    theGraph.addVertex('B'); // 1
  181.  
    theGraph.addVertex('C'); // 2
  182.  
    theGraph.addVertex('D'); // 3
  183.  
    theGraph.addVertex('E'); // 4
  184.  
     
  185.  
    theGraph.addEdge(0, 1, 50); // AB 50
  186.  
    theGraph.addEdge(0, 3, 80); // AD 80
  187.  
    theGraph.addEdge(1, 2, 60); // BC 60
  188.  
    theGraph.addEdge(1, 3, 90); // BD 90
  189.  
    theGraph.addEdge(2, 4, 40); // CE 40
  190.  
    theGraph.addEdge(3, 2, 20); // DC 20
  191.  
    theGraph.addEdge(3, 4, 70); // DE 70
  192.  
    theGraph.addEdge(4, 1, 50); // EB 50
  193.  
     
  194.  
    System.out.println("Shortest paths");
  195.  
    theGraph.path(); // shortest paths
  196.  
    System.out.println();
  197.  
    } // end main()
  198.  
    } // end class PathApp
  199.  
    //代码来自于书《Data Structure & Algorithm in JAVA》
 

四、Floyd(弗洛伊德算法)-解决多源最短路径

1.基本思想

Floyd算法是一个经典的动态规划算法。用通俗的语言来描述的话,首先我们的目标是寻找从点i到点j的最短路径。从动态规划的角度看问题,我们需要为这个目标重新做一个诠释(这个诠释正是动态规划最富创造力的精华所在)。

从任意节点i到任意节点j的最短路径不外乎2种可能,一是直接从i到j,二是从i经过若干个节点k到j。所以,我们假设Dis(i,j)为节点u到节点v的最短路径的距离,对于每一个节点k,我们检查Dis(i,k) + Dis(k,j) < Dis(i,j)是否成立,如果成立,证明从i到k再到j的路径比i直接到j的路径短,我们便设置Dis(i,j) = Dis(i,k) + Dis(k,j),这样一来,当我们遍历完所有节点k,Dis(i,j)中记录的便是i到j的最短路径的距离。

2.基本步骤

  • 首先把初始化距离dist数组为图的邻接矩阵,路径数组path初始化为-1。其中对于邻接矩阵中的数首先初始化为正无穷,如果两个顶点存在边则初始化为权重   
  • 对于每一对顶点 u 和 v,看看是否存在一个顶点 w 使得从 u 到 w 再到 v 比己知的路径更短。如果是就更新它。状态转移方程为
  • 如果 dist[i][k]+dist[k][j] < dist[i][j]
  • 则dist[i][j] = dist[i][k]+dist[k][j]

3.代码

 
  1.  
    //Floyd算法(多源最短路径算法)
  2.  
    bool Floyd(){
  3.  
    for(int k = 1 ; k < this->Nv+1 ; k++){ //k代表中间顶点
  4.  
    for(int i = 1 ; i < this->Nv+1 ; i++){//i代表起始顶点
  5.  
    for(int j = 1 ; j < this->Nv+1 ; j++){//j代表终点
  6.  
    if(this->dist[i][k] + this->dist[k][j] < this->dist[i][j]){
  7.  
    this->dist[i][j] = this->dist[i][k] + this->dist[k][j];
  8.  
    if(i == j && this->dist[i][j] < 0){//发现了负值圈
  9.  
    return false;
  10.  
    }
  11.  
    this->path[i][j] = k;
  12.  
    }
  13.  
    }
  14.  
    }
  15.  
    }
  16.  
    return true;
  17.  
    }
 

五、Floyd-Warshall算法(动态规划)

是解决任意两点间的最短路径的一种算法,时间复杂度为O(N^3),空间复杂度为O(N^2)。可以正确处理有向图或负权的最短路径问题。
设 dist(i,j) 为从节点i到节点j的最短距离若最短路径经过点k,则dist(i,j)=dist(i,k) + dist(k,j),将该路径与先前的dist(i,j)比较获取最小值,即dist(i,j)=min( dist(i,k) + dist(k,j) ,dist(i,j) )。
Floyd-Warshall算法的描述如下:

 
  1.  
    //根据图的邻接矩阵,或邻接链表,初始化dist(i,j)
  2.  
    //其中dist(i,j)表示由点i到点j的代价,当dist(i,j)为 inf 表示两点之间没有任何连接。
  3.  
    For i←1 to n do
  4.  
    For j←1 to n do
  5.  
    dist(i,j) = weight(i,j)
  6.  
    //计算最短路径
  7.  
    for k ← 1 to n do
  8.  
    for i ← 1 to n do
  9.  
    for j ← 1 to n do
  10.  
    if (dist(i,k) + dist(k,j) < dist(i,j)) then // 是否是更短的路径?
  11.  
    dist(i,j) = dist(i,k) + dist(k,j)
 

六、Bellman-Ford(动态规划)

求单源最短路,可以判断有无负权回路(若有,则不存在最短路),时效性较好,时间复杂度O(VE)。
step1:初始化dist(i),除了初始点的值为0,其余都为infinit(表示无穷大,不可到达),pred表示经过的前一个顶点
step2:执行n-1(n等于图中点的个数)次松弛计算:dist(j)=min( dist(i)+weight(i,j),dist(j) )
step3:再重复操作一次,如国dist(j) > distdist(i)+weight(i,j)表示途中存在从源点可达的权为负的回路。
因为,如果存在从源点可达的权为负的回路,则应为无法收敛而导致不能求出最短路径。 
因为负权环可以无限制的降低总花费,所以如果发现第n次操作仍可降低花销,就一定存在负权环。

 
  1.  
    int[] dist=new int[n];
  2.  
    int[] pre=new int[n];
  3.  
     
  4.  
    public void Bellman_Ford(){
  5.  
    //初始化
  6.  
    for(int i=1;i<n-1;i++){
  7.  
    dist[i]=infinit; //TODO
  8.  
    }//end for
  9.  
     
  10.  
    dist[s]=0 //起始点的值
  11.  
     
  12.  
    for (int i=1;i<=n-1;i++){
  13.  
    for(int j=1;j<=edgenum; j++){
  14.  
    if(dist(i)+weight(i,j) <dist(j) ){
  15.  
    dist(j)=dist(i)+weight(i,j);
  16.  
    pred(j)=i;
  17.  
    }//end if
  18.  
    }//end for
  19.  
    }//end for
  20.  
     
  21.  
    //
  22.  
    for(int j=1;j<=edgenum;j++){
  23.  
    if(dist(i)+weight(i,j)<dist()j )
  24.  
    return "有负权回路,不存在最短路径";
  25.  
    }//end for
  26.  
     
  27.  
    }//end Bellman_Ford()
 

七、总结

  1. Dijkstra最短路径算法是基于递推的思想设计的未达顶点的最短路径一定是由已达顶点的最短路径求出。
  2. Floyd最短路径算法只是Dijkstra最短路径算法的加强,其本质还是递推。
  3. Dijkstra求单源、无负权的最短路。时效性较好,时间复杂度为O(V*V+E)。
  4. Floyd求多源、无负权边的最短路。用矩阵记录图。时效性较差,时间复杂度O(V^3)。
  5. Bellman-Ford求单源最短路,可以判断有无负权回路(若有,则不存在最短路),时效性较好,时间复杂度O(VE)。
  6. SPFA是Bellman-Ford的队列优化,时效性相对好,时间复杂度O(kE)。(k<<V)。


我的微信公众号:架构真经(id:gentoo666),分享Java干货,高并发编程,热门技术教程,微服务及分布式技术,架构设计,区块链技术,人工智能,大数据,Java面试题,以及前沿热门资讯等。每日更新哦!

参考资料:

  1. https://www.cnblogs.com/crazily/p/9608448.html
  2. https://blog.csdn.net/yu121380/article/details/79824692
  3. https://blog.csdn.net/yangzhongblog/article/details/8688669
  4. https://blog.csdn.net/qq_30091945/article/details/77964810

猜你喜欢

转载自www.cnblogs.com/anymk/p/11521527.html