最短路径python算法
时间: 2023-10-24 08:17:23 浏览: 37
最短路径算法是一种用于找到两个节点之间最短路径的算法。在计算机科学中,最短路径算法有很多种,包括Dijkstra算法、Bellman-Ford算法、Floyd算法等等。
下面是一个使用Dijkstra算法求解最短路径的Python代码示例:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph} # 初始化距离为无限大
distances[start] = 0 # 起点距离为0
queue = [(0, start)] # 用堆来存储节点和到起点的距离
while queue:
(distance, node) = heapq.heappop(queue) # 取出距离最小的节点
if distance > distances[node]: # 如果这个节点已经被遍历过了则跳过
continue
for neighbor, weight in graph[node].items():
new_distance = distance + weight # 计算新的距离
if new_distance < distances[neighbor]: # 如果新的距离比原来的距离小,则更新距离
distances[neighbor] = new_distance
heapq.heappush(queue, (new_distance, neighbor)) # 把新的节点加入堆中
return distances
# 示例
graph = {
'A': {'B': 2, 'C': 3},
'B': {'A': 2, 'D': 5},
'C': {'A': 3, 'D': 1},
'D': {'B': 5, 'C': 1}
}
print(dijkstra(graph, 'A'))
```
输出结果为:
```
{'A': 0, 'B': 2, 'C': 3, 'D': 4}
```
这意味着从A到B的最短距离为2,从A到C的最短距离为3,从A到D的最短距离为4。