用pathon写出dijikstra
时间: 2024-02-22 17:57:28 浏览: 79
好的,这是一个基于Python的Dijkstra算法示例代码:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和堆
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
heap = [(0, start)]
while heap:
# 弹出堆中最小距离的节点
current_distance, current_vertex = heapq.heappop(heap)
# 如果当前距离已经大于已知最短距离,跳过
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(heap, (distance, neighbor))
return distances
```
其中,`graph`是一个字典类型,表示图的邻接表,`start`是起点节点。示例代码中使用了堆(heap)来优化算法时间复杂度。
阅读全文