用python写一个dijkstra算法
时间: 2024-05-08 19:17:59 浏览: 91
好的,以下是用 Python 写的 Dijkstra 算法样例代码:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = [(0, start)]
while queue:
current_distance, current_node = heapq.heappop(queue)
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(queue, (distance, neighbor))
return distances
```
其中,graph 是一个字典,存储了图中每个节点和它们的邻居及其权重信息,start 是从哪个节点开始计算最短路径。函数返回一个字典,包含从 start 节点出发到图中每个节点的最短路径距离。
希望这个算法能帮到你!
阅读全文