写一个dijskra算法的python代码
时间: 2023-05-12 21:02:39 浏览: 85
数学建模常用的30个常用算法(Python代码).zip
5星 · 资源好评率100%
以下是一个基于Python的Dijkstra算法的实现:
```
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
```
这个函数接受一个字典表示的图和一个起始节点,返回一个字典表示从起始节点到每个节点的最短距离。
阅读全文