python实现迪杰斯特拉算法,并打印最短路径
时间: 2024-10-07 07:02:49 浏览: 31
在Python中,我们可以使用heapq库来实现Dijkstra算法,它可以帮助我们在查找最短路径时保持高效。以下是一个简单的例子,展示了如何找出从起始顶点到所有其他顶点的最短路径:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('infinity') for node in graph}
distances[start] = 0
queue = [(0, start)] # 使用元组存储距离和节点
while queue:
current_distance, current_vertex = heapq.heappop(queue)
if current_distance > distances[current_vertex]:
continue # 如果已经找到了更短的距离,跳过
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(queue, (distance, neighbor)) # 更新队列
return distances
# 假设graph是一个邻接权重字典,如 {(A: [B, C], B: [A, D], ...)}
graph = {...}
shortest_distances = dijkstra(graph, 'A')
print("从A出发的最短路径:")
for vertex, distance in shortest_distances.items():
print(f"{vertex}: {distance}")
阅读全文