Python最短路径算法
时间: 2023-11-29 14:44:45 浏览: 73
python编写的最短路径算法
5星 · 资源好评率100%
以下是Python中实现Dijkstra算法求解最短路径的示例代码:
```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是起点。示例代码中使用了堆来优化算法的效率。
阅读全文