python 打字代码
时间: 2023-10-12 13:55:14 浏览: 86
python代码
以下是Python实现Dijkstra算法的代码:
```python
import heapq
def dijkstra(graph, start):
# 初始化距离字典和堆
distances = {node: float('inf') for node in graph}
distances[start] =
heap = [(, start)]
while heap:
# 取出堆中距离最小的节点
(current_distance, current_node) = heapq.heappop(heap)
# 如果当前节点已经被处理过,则跳过
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(heap, (distance, neighbor))
return distances
```
其中,`graph`是一个字典,表示图的邻接表,`start`是起点节点。算法返回一个字典,表示每个节点到起点的最短距离。
阅读全文