G = {1: {1: 0, 2: 10, 4: 30, 5: 100}, 2: {2: 0, 3: 50}, 3: {3: 0, 5: 10}, 4: {3: 20, 4: 0, 5: 60}, 5: {5: 0}, } INF = 999999999 dis = dict((key, INF) for key in G) start=1 dis[start] = 0 visted_point = dict((key, False) for key in G) pq = [] pq.append((start,dis[start])) visted_point[start] = True while list(visted_point.values())!=[True]*len(visted_point): tmp=[] for node in G[pq[-1][0]]: new_dis = dis[pq[-1][0]] + float(G[pq[-1][0]][node]) if new_dis < dis[node] and (not visted_point[node]): dis[node] = new_dis visted_point[node]=True tmp.append((node,new_dis)) if len(tmp)>0: tmp = sorted(tmp, key=lambda x: x[1]) pq.append((tmp[0])) print(dis)
python 最短路径
最新推荐文章于 2024-06-04 10:12:07 发布