迪克斯特拉算法的python实现
时间: 2023-12-06 21:37:57 浏览: 102
以下是迪克斯特拉算法的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`是起点。函数返回一个字典,表示起点到各个节点的最短距离。
阅读全文