python实现Dijkstra算法,请为我写一下它的代码
时间: 2024-05-13 18:20:20 浏览: 86
好的,以下是Python实现Dijkstra算法的代码:
```
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}
# 初始化堆和访问集合
visited = set()
heap = [(0, start)]
while heap:
# 弹出堆中距离最小的节点
(current_distance, current_vertex) = heapq.heappop(heap)
# 如果节点已被访问,则跳过
if current_vertex in visited:
continue
# 将当前节点添加到访问集合中
visited.add(current_vertex)
# 如果节点是终点,则返回结果
if current_vertex == end:
path = []
while previous_vertices[current_vertex] is not None:
path.append(current_vertex)
current_vertex = previous_vertices[current_vertex]
path.append(start)
path.reverse()
return path, distances[end]
# 更新相邻节点距离和前驱节点信息
for neighbor, weight in graph[current_vertex].items():
if neighbor in visited:
continue
new_distance = current_distance + weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
previous_vertices[neighbor] = current_vertex
heapq.heappush(heap, (new_distance, neighbor))
# 如果未找到终点,则返回None
return None, None
```
其中,graph表示图的邻接矩阵,start表示起始节点,end表示终止节点。函数返回从起点到终点的最短路径和距离。
阅读全文