- 题目用到的图
- 具体代码
# -*- coding:utf-8 -*- """ Author: leadingme Mail:leadingme@qq.com MyWebsite:leadingme.top """ from queue import PriorityQueue import math graph = { "A": {"B":5,"C":1}, "B": {"A":5,"C":2,"D":1}, "C": {"A":1,"B":2,"D":4,"E":8}, "D": {"B":1,"C":4,"E":3,"F":6}, "E": {"C":8,"D":3}, "F": {"D":6} } def init_distance(graph, s): distance = {s:0} for vertex in graph: if vertex != s: distance[vertex] = math.inf return distance def dijksra(graph, s): pq = PriorityQueue(maxsize=0) pq.put((0,s)) seen = set() parent = {s: None} # 用于存储每个节点的父节点,求最短距离可用 distance = init_distance(graph, s) # 用于存储每个节点 while pq.qsize() > 0: # 队列判空 pair = pq.get() dist, vertex = pair[0], pair[1] seen.add(vertex) # 经过优先队列排序后再弹出的值 nodes = graph[vertex].keys() for w in nodes: if w not in seen: if dist + graph[vertex][w] < distance[w]: pq.put((dist + graph[vertex][w], w)) parent[w] = vertex distance[w] = dist + graph[vertex][w] return parent, distance if __name__ == '__main__': parent, distance = dijksra(graph, "A") # 例: E 到 C 的距离 pre = next = "E" dist = 0 while next != "C": next = parent[next] dist += graph[pre][next] pre = next print("They are distance is %d." %dist)
带权重图中两点的最短距离(优先队列实现)
最新推荐文章于 2022-11-08 10:24:04 发布