python最短路径算法 - Dijkstra算法
时间: 2023-11-29 17:47:01 浏览: 106
Dijkstra算法(最短路径)
4星 · 用户满意度95%
以下是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`是起点结点。示例代码中使用了堆来优化算法,使得时间复杂度为$O(E\log V)$,其中$E$为边数,$V$为结点数。
阅读全文