dijsktra函数代码
时间: 2024-05-08 09:21:17 浏览: 50
以下是Dijkstra算法的Python实现:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典,将所有节点距离设置为无穷大,起点距离为0
dist = {node: float('inf') for node in graph}
dist[start] = 0
# 初始化堆,将起点加入堆中
heap = [(0, start)]
while heap:
# 取出堆顶元素
(curr_dist, curr_node) = heapq.heappop(heap)
# 如果当前节点已经被处理过,忽略它
if curr_dist > dist[curr_node]:
continue
# 遍历当前节点的邻居节点
for neighbor, weight in graph[curr_node].items():
# 计算从起点到邻居节点的距离
new_dist = dist[curr_node] + weight
# 如果新的距离比已有的距离更短,则更新距离字典和堆
if new_dist < dist[neighbor]:
dist[neighbor] = new_dist
heapq.heappush(heap, (new_dist, neighbor))
return dist
```
其中,`graph`是一个字典,键为节点,值为该节点的邻居节点和对应的边权重。`start`是起点节点。函数返回一个字典,键为节点,值为起点到该节点的最短距离。
阅读全文