dijkstra算法python求最短路径
时间: 2023-12-26 19:26:03 浏览: 28
以下是使用Python实现Dijkstra算法求最短路径的示例代码:
```python
import heapq
def dijkstra(graph, start, end):
# 初始化距离字典和前驱节点字典
distances = {vertex: float('inf') for vertex in graph}
distances[start] = 0
previous_vertices = {vertex: None for vertex in graph}
# 将起始节点加入堆中
vertices = [(0, start)]
heapq.heapify(vertices)
while vertices:
# 取出堆中距离最小的节点
current_distance, current_vertex = heapq.heappop(vertices)
# 如果当前节点已经处理过,跳过
if current_distance > distances[current_vertex]:
continue
# 遍历当前节点的邻居节点
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
# 如果发现更短的路径,则更新距离和前驱节点
if distance < distances[neighbor]:
distances[neighbor] = distance
previous_vertices[neighbor] = current_vertex
# 将邻居节点加入堆中
heapq.heappush(vertices, (distance, neighbor))
# 构造最短路径
path = []
vertex = end
while vertex is not None:
path.append(vertex)
vertex = previous_vertices[vertex]
path.reverse()
return path, distances[end]
# 示例
graph = {
'A': {'B': 2, 'C': 1},
'B': {'A': 2, 'D': 3, 'E': 2},
'C': {'A': 1, 'F': 4},
'D': {'B': 3},
'E': {'B': 2, 'F': 3},
'F': {'C': 4, 'E': 3}
}
start = 'A'
end = 'F'
path, distance = dijkstra(graph, start, end)
print('最短路径:', path)
print('最短距离:', distance)
```