Dijkstra算法的Python代码
时间: 2023-11-12 15:11:02 浏览: 77
以下是Dijkstra算法的Python代码:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和堆
distances = {node: float('inf') for node in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
# 从堆中弹出距离最短的节点
(current_distance, current_node) = heapq.heappop(heap)
# 如果当前节点的距离已经大于已知的最短距离,则忽略
if current_distance > distances[current_node]:
continue
# 对当前节点的所有邻居进行松弛操作
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(heap, (distance, neighbor))
return distances
```
其中,`graph`是一个邻接表表示法的图,`start`是起点。算法返回一个字典,其中每个节点的键值对表示该节点到起点的最短距离。
阅读全文