python单源最短路径——dijkstra算法
时间: 2023-12-22 20:29:45 浏览: 159
离字典,将起始节点的距离设为0,其他节点的距离设为无穷大
distances = {node: sys.maxsize for node in graph}
distances[start] = 0
# 初始化已访问节点的集合和未访以下是使用问节点D的集ijkstra合
visited = set()
unvisited算法求解最短路径的Python = set(graph)
while unvisited:
# 代码示例:
```python
class D选择当前ijkstra距:
def __init__(self, graph离最小的节点
, start, current goal):
self.graph = graph # 邻接表_node = min(unvisited,
key=lambda self node: distances[node])
# 更新.start = start当前节点的 # 起邻居节点点
self.goal =的距离 goal # 终点
for neighbor in graph self.open[current_node]:
_list = {} if neighbor in # open 表
self.closed_list unvisited:
new_distance = distances[current_node] + = {} graph[current_node][neighbor # closed 表
self.open_list[start]
if new_distance] = < distances[neighbor]:
0.0 # 将 distances[neighbor] = new_distance
# 将当前起点放入 open_list 中
self.parent = {节点标记start:为已访 None} 问,并从未访问集合中移除
visited.add # 存储节点的父子关系。键为(current_node)
子节点, unvisited值为父.remove(current_node)
return节点。方便做最 distances
def print后_path(dist路径的ances,回 start溯
self.min, end):
_dis = None # 根 # 最短路径的长度
def shortest_path据距离字典和终点节点(self):
while True:
,逆向 if self打印路径.open_list is
path = [end None:
]
print('搜索 current_node =失败 end
while current_node !=, 结束!')
break
distance start:
, min_node = for neighbor in graph min(zip[current_node]:
if(self.open_list distances[current.values(), self_node] ==.open_list.keys distances[neighbor())) #] + graph 取出距[neighbor][current_node]:
离最小的节点
self path.open_list.pop.append(min_node)(neighbor)
current_node = neighbor
break
path.reverse()
# 将其从 open_list 中去除
self print.closed("_list[minShortest_node] = path from", distance # 将节点加入 closed start, "to", end,_list ":", "->".join(path))
# 示例 中
if min_node == self.goal: # 如果节点为图的邻接矩阵终点
self.min_dis = distance
表示
graph shortest = {
_path = [ 'Aself.goal]': {'B': # 5, 'C 记录从': 终1},
点回溯的路径 'B
阅读全文