(Dijkstra)算法python代码
时间: 2023-12-08 16:04:16 浏览: 131
Python语言编写的Dijkstra算法
以下是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`是起点。函数返回一个字典,表示起点到各个节点的最短距离。
阅读全文