用python写dijkstra求最短路径代码
时间: 2024-02-18 18:30:24 浏览: 79
Dijkstra算法找最短路径代码,dijkstra算法求最短路径,matlab
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:
(current_distance, current_node) = heapq.heappop(pq)
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(pq, (distance, neighbor))
return distances
```
其中,参数 `graph` 表示的是用字典表示的图,例如:{'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2}, 'C': {'A': 4, 'B': 2, 'D': 3}, 'D': {'C': 3}}。参数 `start` 表示起点。函数返回值是一个字典,表示从起点到每个节点的最短路径长度。
希望能够帮到你!
阅读全文