1 def Dijkstra(network,s,d):#迪傑斯特拉算法算s-d的最短路徑,並返回該路徑和代價 2 print("Start Dijstra Path……") 3 path=[]#s-d的最短路徑 4 n=len(network)#鄰接矩陣維度,即節點個數 5 fmax=999 6 w=[[0 for i in range(n)]for j in range(n)]#鄰接矩陣轉化成維度矩陣,即0→max 7 book=[0 for i in range(n)]#是否已是最小的標記列表 8 dis=[fmax for i in range(n)]#s到其餘節點的最小距離 9 book[s-1]=1#節點編號從1開始,列表序號從0開始 10 midpath=[-1 for i in range(n)]#上一跳列表 11 for i in range(n): 12 for j in range(n): 13 if network[i][j]!=0: 14 w[i][j]=network[i][j]#0→max 15 else: 16 w[i][j]=fmax 17 if i==s-1 and network[i][j]!=0:#直連的節點最小距離就是network[i][j] 18 dis[j]=network[i][j] 19 for i in range(n-1):#n-1次遍歷,除了s節點 20 min=fmax 21 for j in range(n): 22 if book[j]==0 and dis[j]<min:#若是未遍歷且距離最小 23 min=dis[j] 24 u=j 25 book[u]=1 26 for v in range(n):#u直連的節點遍歷一遍 27 if dis[v]>dis[u]+w[u][v]: 28 dis[v]=dis[u]+w[u][v] 29 midpath[v]=u+1#上一跳更新 30 j=d-1#j是序號 31 path.append(d)#由於存儲的是上一跳,因此先加入目的節點d,最後倒置 32 while(midpath[j]!=-1): 33 path.append(midpath[j]) 34 j=midpath[j]-1 35 path.append(s) 36 path.reverse()#倒置列表 37 print(path) 38 #print(midpath) 39 print(dis) 40 #return path 41 42 network=[[0,1,0,2,0,0], 43 [1,0,2,4,3,0], 44 [0,2,0,0,1,4], 45 [2,4,0,0,6,0], 46 [0,3,1,6,0,2], 47 [0,0,4,0,2,0]] 48 Dijkstra(network,1,6)