2019-09-19 13:07:02 5064瀏覽
今天千鋒扣丁學堂Python培訓老師給大家分享一篇關于Dijkstra算法實現最短路徑問題的方法的詳細介紹,文中通過示例代碼介紹的非常詳細,下面我們一起來看一下吧。#構造有向圖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))
請輸入源點 a 請輸入終點 f 從頂點a到頂點f的最短路徑為: ['a', 'c', 'e', 'f'] 最短路徑長度為:17
【關注微信公眾號獲取更多學習資料】 【掃碼進入Python全棧開發免費公開課】