帮我用Python写个二叉堆优化的戴克斯特拉算法
时间: 2023-02-20 21:13:14 浏览: 78
好的,以下是使用 Python 实现的带二叉堆优化的 Dijkstra 算法的代码:
```
import heapq
from collections import defaultdict
def dijkstra(graph, start):
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
(current_distance, current_vertex) = heapq.heappop(heap)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(heap, (distance, neighbor))
return distances
if __name__ == "__main__":
graph = defaultdict(dict)
graph['A']['B'] = 1
graph['A']['C'] = 4
graph['B']['C'] = 2
graph['B']['D'] = 5
graph['C']['D'] = 1
print(dijkstra(graph, 'A'))
```
希望对您有所帮助!
阅读全文