Dijkstra算法可以计算出在有权图中从某个起点出发到其他任何一点的最短路径长度
算法思想:
迪杰斯特拉算法主要特点是从起始点开始,采用贪心算法的策略,每次遍历到始点距离最近且未访问过的顶点的邻接节点,直到扩展到终点为止。
定义起点s,终点t,集合U表示还没有找到起点到该点的最短路径的点的集合,集合S表示已经找到最短路径的点的集合,初始情况下S集合中只有起点一个点,最短路径是0
1 # -*- coding: utf-8 -*- 2 """ 3 Created on Wed Jul 12 17:02:54 2023 4 5 @author: SunYuhui 6 """ 7 import numpy as np 8 9 def Dijkstra(Network,s,d):#迪杰斯特拉算法算s-d的最短路径,并返回该路径和代价 10 Network = np.array(Network) 11 NetShape = Network.shape 12 13 start = s #起点 14 destination = d #终点 15 16 # 对于S,第二列表示从源节点到本节点已求得的最小距离,不再变更; 17 #S = [0节点 1父节点 2距离] ps:距离 是到起点的距离 18 S = np.array([[start,-1,0]]) 19 20 21 # 对于U,第二列表示从源节点到本节点暂时求得的最小距离,可能会变更 22 U = np.zeros((NetShape[0],3)) 23 U[:,0] = [i for i in range(NetShape[0])] 24 U[:,1] = -1 25 U[:,2] = float("inf") 26 U = np.delete(U, start, axis=0) 27 28 while U.shape[0] > 0: 29 #更新U #更新父节点 #更新距离 30 U_shape = U.shape 31 32 for i in range(U_shape[0]): 33 if Network[int(S[-1,0]),int(U[i,0])] != float("inf")\ 34 and Network[int(S[-1,0]),int(U[i,0])]+S[-1,2] < U[i,2]: 35 U[i,1] = S[-1,0] #更新父节点 36 U[i,2] = Network[int(S[-1,0]),int(U[i,0])] + S[-1,2] #更新距离 37 38 #选择距离最小 39 idx = np.argmin(U[:,2]) 40 #更新S:添加被选择的点 进 S 41 S = np.row_stack((S, U[idx,:])) 42 #更新U:删除掉被选择的节点 43 U = np.delete(U, idx, axis=0) 44 45 #回溯求最短路径 46 path = np.array([destination]) 47 while True: 48 index = np.where(S[:,0] == path[path.shape[0]-1]) 49 path = np.append(path,S[index,1]) 50 if S[index,1] == start: 51 break 52 path = np.flip(path) 53 54 #求最短距离 55 index = np.where(S[:,0] == destination) 56 mindist = S[index,2] 57 return path,mindist 58 59 # Network = [[float("inf"),3,float("inf"),1,2,float("inf")], 60 # [3,float("inf"),float("inf"),float("inf"),float("inf"),2], 61 # [float("inf"),float("inf"),float("inf"),3,1,float("inf")], 62 # [1,float("inf"),3,float("inf"),float("inf"),2], 63 # [2,float("inf"),1,float("inf"),float("inf"),float("inf")], 64 # [float("inf"),2,float("inf"),2,float("inf"),float("inf")]] 65 # dic = ['a','b','c','d','u','v'] 66 # s=4 67 # d=5 68 #最优路径uadv 69 #最短距离5 70 71 Network = [[float("inf"),12,float("inf"),float("inf"),float("inf"),16,14], 72 [12,float("inf"),10,float("inf"),float("inf"),7,float("inf")], 73 [float("inf"),10,float("inf"),3,5,6,float("inf")], 74 [float("inf"),float("inf"),3,float("inf"),4,float("inf"),float("inf")], 75 [float("inf"),float("inf"),5,4,float("inf"),2,8], 76 [16,7,6,float("inf"),2,float("inf"),9], 77 [14,float("inf"),float("inf"),float("inf"),8,9,float("inf")]] 78 dic = ['A','B','C','D','E','F','G'] 79 s=3 80 d=0 81 path,mindist = Dijkstra(Network,s,d) 82 #最优路径DEFA 83 #最短距离22 84 85 86 result = '' 87 for i in range(path.shape[0]): 88 result = result + dic[int(path[i])] 89 print("最优路径:"+result) 90 print("最短距离:"+str(int(mindist)))
参考资料:
Matlab复现迪杰斯特拉算法 - junlin623 - 博客园 (cnblogs.com)
标签:Network,python,float,迪杰,int,斯特拉,np,path,inf From: https://www.cnblogs.com/syhui/p/17550139.html