2019-09-19 13:07:02 5045瀏覽
今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于Dijkstra算法實(shí)現(xiàn)最短路徑問題的方法的詳細(xì)介紹,文中通過示例代碼介紹的非常詳細(xì),下面我們一起來看一下吧。#構(gòu)造有向圖Graph class Graph: def __init__(self,graph,labels): #labels為標(biāo)點(diǎn)名稱 self.Arcs=graph self.VertexNum=graph.shape[0] self.labels=labels def Dijkstra(self,Vertex,EndNode): #Vertex為源點(diǎn),EndNode為終點(diǎn) Dist=[[] for i in range(self.VertexNum)] #存儲(chǔ)源點(diǎn)到每一個(gè)終點(diǎn)的最短路徑的長度 Path=[[] for i in range(self.VertexNum)] #存儲(chǔ)每一條最短路徑中倒數(shù)第二個(gè)頂點(diǎn)的下標(biāo) flag=[[] for i in range(self.VertexNum)] #記錄每一個(gè)頂點(diǎn)是否求得最短路徑 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 #表示從頂點(diǎn)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集合中找出的距離源點(diǎn)Vertex最斷路徑的頂點(diǎn) MinDist=Dist[j] j+=1 flag[tVertex]=1 EndVertex=0 MinDist=float('inf') #表示無窮大,若兩點(diǎn)間的距離小于MinDist說明兩點(diǎn)間有路徑 #更新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=[] #存儲(chǔ)從源點(diǎn)到終點(diǎn)的最短路徑 return Dist[EndNode],start_end_Path(Path,Vertex,EndNode,vertex_endnode_path) #根據(jù)本文上述定義的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('請(qǐng)輸入源點(diǎn)') endnode=input('請(qǐng)輸入終點(diǎn)') 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('從頂點(diǎn){}到頂點(diǎn){}的最短路徑為:\n{}\n最短路徑長度為:{}'.format(start,endnode,Path,dist))
請(qǐng)輸入源點(diǎn) a 請(qǐng)輸入終點(diǎn) f 從頂點(diǎn)a到頂點(diǎn)f的最短路徑為: ['a', 'c', 'e', 'f'] 最短路徑長度為:17
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】
查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>