赞
踩
def Dijkstra(G, start): """ """ nodes_num = len(G) start = start - 1 inf = float('inf') visited = [0] * nodes_num # 初始dis为初始点到各结点的距离 dis = {node: G[start][node] for node in range(nodes_num)} # 初始parents为初始结点到本结点寻找最短路径时,本节点的上一个最优结点 parents = {node: [-1] for node in range(nodes_num)} visited[start] = 1 last_point = start for i in range(nodes_num - 1): min_dis = inf for j in range(nodes_num): if visited[j] == 0 and dis[j] < min_dis: min_dis = dis[j] last_point = j visited[last_point] = 1 if i == 0: parents[last_point][0] = start + 1 for k in range(nodes_num): if G[last_point][k] < inf: if dis[k] > G[last_point][k] + dis[last_point]: parents[k] = [last_point + 1] dis[k] = G[last_point][k] + dis[last_point] elif G[last_point][k] != 0 and dis[k] == G[last_point][k] + dis[last_point]: parents[k].append(last_point + 1) return {key + 1: val for key, val in dis.items()}, {key + 1: val for key, val in parents.items()} if __name__ == '__main__': # 二维数组 # 设初始顶点为pe1 # pe1 pe4 pe6 pe2 pe5 pe3 # 1 4 6 2 5 3 # 1 0 inf inf 1 inf 12 # 4 inf 0 15 inf 9 4 # 6 inf inf 0 inf inf inf # 2 inf 3 inf 0 inf 9 # 5 inf inf 4 inf 0 inf # 3 inf inf inf inf 5 0 vals = { -1: 'pe1', 1: 'pe1', 2: 'pe4', 3: 'pe6', 4: 'pe2', 5: 'pe5', 6: 'pe3' } inf = float('inf') G = [[0, inf, inf, 1, inf, 12], # pe1 [inf, 0, 15, inf, 9, 4], # pe4 [inf, inf, 0, inf, inf, inf], # pe6 [inf, 3, inf, 0, inf, 9], # pe2 [inf, inf, 4, inf, 0, inf], # pe5 [inf, inf, inf, inf, 5, 0] # pe3 ] # 二维数组的初始结点到各个结点的出发顺序为1, 4, 6, 2, 5, 3 dis, parents = Dijkstra(G, 1) # print(parents) # 初始点到各个结点的最短距离 print({vals[key]: val for key, val in dis.items()}) print({vals[key]: [vals[v] for v in val ] for key, val in parents.items()})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。