最短路径算法 Floyd算法 Dijkstra算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35774189/article/details/84580487

1、Floyd算法解决的是所有成对的最短路径问题

对于图中的每一个顶点,该算法都会找出从某个顶点到该顶点所能达到的任何其他顶点的最短路径

构建的一个初始的距离矩阵,其单元格中包含了连接每一个顶点及其邻居节点的边的权重。当两个顶点之间没有直接的边的时候,我们会在矩阵的单元格中放置一个表示无限的值。

Floyd算法的伪代码:

for i from 0 to n-1

       for r from 0 to n-1

             for c from 0 to n-1

                  matrix[r][c]=min(matrix[r][c],matrix[r][i]+matrix[i][c])

2、Dijkstra算法

该算法的输入是一个有向图,且该有向图带有权重大于0的边,以及表示原顶点的一个单顶点。该算法计算从源顶点到图中所有其他顶点之间的最短路径的距离。算法的输出是一个二维的表格results。这个表格有N行,而N是图中的顶点的数目。每一行的第一列包含一个顶点。第二列包含了从源顶点到这个顶点的距离。第三列包含了这条路径上的直接父顶点。

扫描二维码关注公众号,回复: 5010061 查看本文章

除了这个表格,算法还使用看一个临时的列表included,它包含了N个布尔值,用来记录给定的顶点是否已经包含到了顶点的一个集合中,而这个集合已经用来确定过最短路径了。

该算法包含两个主要步骤,一个初始化步骤和一个计算步骤:

初始化步骤:

在这个步骤中,根据以下的算法,初始化results表格中的所有列和included列表中的所有单元格。

for each vertex in the graph

     Store vertex in the current row of the results grid

     If vertex = source vertex 

          Set the row's distance cell to 0

          Set the row's parent cell to undefined

          Set included[row] to True

     Else if there is an edge from source vertex to vertex

          Set the row's distance cell to the edge's weight

          Set the row's parent cell to source vertex

          Set included[row] to False

     Else 

          Set the row's distance cell to infinity

          Set the row's parent cell to undefined

          Set included[row] to False

Go to the next row in the results grid

在这个过程结束后,达到如下的一下效果:

  • included列表中的单元格,除了与results表格中的源顶点的行对应的单元格,其余的为False.
  • 一行的距离(distance)单元格中,可能有0(对于源顶点)、无限(如果没有从源顶点开始的一条直接的边连接到这个顶点的话)、或者为一个正数(如果有一条从源顶点开始的直接的边连接到这个顶点)
  • 一行的父(parent)单元格中的顶点,要么是源顶点,要么未定义。在实现中使用None来表示未定义

计算步骤:

在计算步骤中,Dijkstra算法会找出从单源顶点到一个顶点的最短路径,在included列表中标记这个顶点的单元格,并且继续这个过程,直到所有的单元格都标记完了。

如下是该步骤的算法。

Do

       Find the vertex F that is not yet included and has the minimal

       distance in the results grid 

       Mark F as included 

       For each other vertex T not included 

             If there is an edge from F to T

                  Set new distance to F's distance + edge's weight

                  If new distance < T's distance in the results grid 

                        Set T's distance to new distance 

                        Set T's parent in the results grid to F

While at least one vertex is not included

该算法重复地选取那些还没有被包含且具有最短路径距离的顶点,并且将其标记为包含,然后再进入到嵌套的for循环中。在这个循环体中,该过程会遍历从包含的顶点到未包含的顶点的任何的边,并且确定从源顶点到任何这些其他节点的最小的可能距离。这个过程中重要步骤是嵌套的if语句,如果找到了从包含的顶点到未包含的顶点的一个新的最小距离的话,它会为未包含的顶点重要距离和父单元格。

猜你喜欢

转载自blog.csdn.net/qq_35774189/article/details/84580487