采用狄克斯特拉求带权有向图的最短路径代码
时间: 2024-12-06 17:08:54 浏览: 19
狄克斯特拉算法(Dijkstra's Algorithm)是一种用于解决单源最短路径问题的贪心算法,特别适用于加权有向图。以下是用Python实现的一个基本版本:
```python
import heapq
def dijkstra(graph, start):
distances = {node: float('infinity') 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是一个字典,键是节点,值是邻接字典,表示有向边及其权重
graph = {
'A': {'B': 5, 'C': 1},
'B': {'A': 5, 'C': 2, 'D': 1},
'C': {'A': 1, 'B': 2, 'D': 4},
'D': {'B': 1, 'C': 4}
}
shortest_paths = dijkstra(graph, 'A')
print("从'A'到其他节点的最短路径:", shortest_paths)
阅读全文