基于python的dijkstra算法实现
时间: 2023-12-16 07:51:12 浏览: 76
python实现的dijkstra算法路径规划源码.zip
5星 · 资源好评率100%
以下是基于python的dijkstra算法实现代码:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
(dist, current_node) = heapq.heappop(pq)
if dist > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
# example usage
graph = {
'A': {'B': 2, 'C': 4},
'B': {'D': 3},
'C': {'D': 1, 'E': 5},
'D': {'E': 1},
'E': {}
}
print(dijkstra(graph, 'A'))
```
运行结果:
```
{'A': 0, 'B': 2, 'C': 4, 'D': 5, 'E': 6}
```
该代码实现了dijkstra算法,输入为一个图和起点,返回一个字典,其中键为节点,值为该节点到起点的距离。该算法使用了优先队列来优化寻找最短路径的过程。时间复杂度为O(ElogV),其中E为边数,V为节点数。
阅读全文