写出Dijkstra算法代码
时间: 2023-10-04 21:12:33 浏览: 94
Python实现Dijkstra算法
以下是Python实现的Dijkstra算法代码:
```
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
visited = set()
while pq:
(distance, node) = heapq.heappop(pq)
if node in visited:
continue
visited.add(node)
for neighbor, weight in graph[node].items():
distance_to_neighbor = distance + weight
if distance_to_neighbor < distances[neighbor]:
distances[neighbor] = distance_to_neighbor
heapq.heappush(pq, (distance_to_neighbor, neighbor))
return distances
```
其中,graph是一个字典,表示有向图,每个节点对应一个字典,存储它的邻居节点及边权重。例如:
```
graph = {
'A': {'B': 2, 'C': 4},
'B': {'C': 1, 'D': 4},
'C': {'D': 1},
'D': {}
}
```
start表示起点。算法返回一个字典distances,表示从起点到每个节点的最短距离。
阅读全文