迪杰斯特拉算法 python代码实现有向图
时间: 2024-09-20 07:00:26 浏览: 49
迪杰斯特拉(Dijkstra's Algorithm)是一种用于寻找图中两点之间最短路径的算法,通常应用于带权重的有向图或无向图。以下是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
# 示例:有向图的邻接矩阵表示,其中weights是从start到end的距离
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
start = 'A'
shortest_distances = dijkstra(graph, start)
print("从{}到各个节点的最短距离: {}".format(start, shortest_distances))
阅读全文