请用Python写一段迪杰斯特拉算法
时间: 2023-05-15 20:06:40 浏览: 94
迪杰斯特拉算法
以下是Python实现的迪杰斯特拉算法:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
current_distance, current_node = heapq.heappop(pq)
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(pq, (distance, neighbor))
return distances
```
其中,`graph`是一个字典,表示图的邻接表,`start`是起点。函数返回一个字典,表示从起点到各个节点的最短距离。
阅读全文