Methods python Dijkstra's shortest path algorithm

This article describes how python Dijkstra shortest path algorithm, the paper sample code described in great detail, has a certain reference value of learning for all of us to learn or work, we need friends with Xiao Bian below to learn together learn it
points from a source to each vertex of the shortest path remaining
Dijkstra algorithm can be used to solve a drawing source shortest path to the rest of the vertices. Suppose G = {V, {E} } contains n vertices in a directed graph, in which FIG vertex v is the source point, the Dijkstra algorithm for finding vertex v to FIG remaining basic idea of the respective shortest path vertices follows:

The set S is determined using the recording end point of the shortest path, the initial S = {v}.
Selecting a minimum length of the shortest path, the path end point belongs VS w, w will be incorporated into S, and the length of the shortest path is referred to as Dw.
For any of the VS is a vertex s, the length of the shortest path to the source s of the vertex referred to as Ds, and an arcuate vertex weight vertices w value of s is denoted Dws, if Dw + Dws <Ds,
then the source point vertex s to modify the path length Dw + Ds = ws.
Repeat 2 and 3, known S = V.
In order to realize the algorithm,
using the adjacency matrix Arcs are stored to the network, when i = j when, Arcs [i] [j] = 0;! When i = j time, if the labeled vertex i to index the vertex j of and arc arc has a weight of w, the arcs [i] [j] = w, or arcs [i] [j] = float ( 'inf') i.e., infinity.
Dist used to store source shortest path length of each end.
Each shortest path penultimate vertex index list using the stored Path.
Use flag record whether each vertex shortest path has been obtained, that is determined in thought vertex set V belongs, or belong to the set of VS.
Code

#构造有向图Graph
class Graph:
  def __init__(self,graph,labels): #labels为标点名称
    self.Arcs=graph
    self.VertexNum=graph.shape[0]
    self.labels=labels
def Dijkstra(self,Vertex,EndNode): #Vertex为源点,EndNode为终点
  Dist=[[] for i in range(self.VertexNum)] #存储源点到每一个终点的最短路径的长度
  Path=[[] for i in range(self.VertexNum)] #存储每一条最短路径中倒数第二个顶点的下标
  flag=[[] for i in range(self.VertexNum)] #记录每一个顶点是否求得最短路径
  index=0
  #初始化
  while index<self.VertexNum:
    Dist[index]=self.Arcs[Vertex][index]
    flag[index]=0
    if self.Arcs[Vertex][index]<float('inf'): #正无穷
      Path[index]=Vertex
    else:
      Path[index]=-1 #表示从顶点Vertex到index无路径
    index+=1
  flag[Vertex]=1
  Path[Vertex]=0
  Dist[Vertex]=0
  index=1
  while index<self.VertexNum:
    MinDist=float('inf')
    j=0
    while j<self.VertexNum:
      if flag[j]==0 and Dist[j]<MinDist:
        tVertex=j #tVertex为目前从V-S集合中找出的距离源点Vertex最断路径的顶点
        MinDist=Dist[j]
      j+=1
    flag[tVertex]=1
    EndVertex=0
    MinDist=float('inf') #表示无穷大,若两点间的距离小于MinDist说明两点间有路径
    #更新Dist列表,符合思想中第三条
    while EndVertex<self.VertexNum:
      if flag[EndVertex]==0:
        if self.Arcs[tVertex][EndVertex]<MinDist and Dist[
          tVertex]+self.Arcs[tVertex][EndVertex]<Dist[EndVertex]:
          Dist[EndVertex]=Dist[tVertex]+self.Arcs[tVertex][EndVertex]
          Path[EndVertex]=tVertex
      EndVertex+=1
    index+=1
  vertex_endnode_path=[] #存储从源点到终点的最短路径
  return Dist[EndNode],start_end_Path(Path,Vertex,EndNode,vertex_endnode_path)
#根据本文上述定义的Path递归求路径
def start_end_Path(Path,start,endnode,path):
  if start==endnode:
    path.append(start)
  else:
    path.append(endnode)
    start_end_Path(Path,start,Path[endnode],path)
  return path
 
if __name__=='__main__':
  #float('inf')表示无穷
  graph=np.array([[0,6,5,float('inf'),float('inf'),float('inf')],
          [float('inf'),0,2,8,float('inf'),float('inf')],
          [float('inf'),float('inf'),0,float('inf'),3,float('inf')],
          [float('inf'),float('inf'),7,0,float('inf'),9],
          [float('inf'),float('inf'),float('inf'),float('inf'),0,9],
          [float('inf'),float('inf'),float('inf'),float('inf'),0]])
  G=Graph(graph,labels=['a','b','c','d','e','f'])
  start=input('请输入源点')
  endnode=input('请输入终点')
  dist,path=Dijkstra(G,G.labels.index(start),G.labels.index(endnode))
  Path=[]
  for i in range(len(path)):
    Path.append(G.labels[path[len(path)-1-i]])
  print('从顶点{}到顶点{}的最短路径为:\n{}\n最短路径长度为:{}'.format(start,endnode,Path,dist))

Output:

请输入源点
a
请输入终点
f
从顶点a到顶点f的最短路径为:
['a', 'c', 'e', 'f']
最短路径长度为:17

We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, sharing some learning methods and the need to pay attention to small details, click on Join us python learner gathering
is more than the entire contents of this article, we want to help learning,

Published 30 original articles · won praise 10 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun06/article/details/104485974