
image.png
graph = {} # 存储所有节点的所有邻居和前往邻居的开销
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
print(graph) # {'a': {'fin': 1}, 'start': {'a': 6, 'b': 2}, 'b': {'a': 3, 'fin': 5}, 'fin': {}}
infinity = float("inf") # 无穷大
costs = {} # 存储前往各个点的开销
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity #到终点的开销初始值为无限大
parents = {} #存储各个节点的父节点
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None #终点的父节点初始值为空
processed = [] # 保存已处理过的节点
#找出开销最小的节点
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
node = find_lowest_cost_node(costs) #在未处理的节点中找出开销最小的节点
while node is not None:
cost = costs[node] # cost = 当前节点的开销
neighbors = graph[node] #neighbors = 当前节点的邻居和开销
for n in neighbors.keys(): #遍历当前节点的所有邻居
new_cost = cost + neighbors[n] # new_cost = 从起点到达邻居n的开销
if costs[n] > new_cost: #如果之前记录的邻居n开销大于此次计算的
costs[n] = new_cost # 重新设置邻居n的开销
parents[n] = node # 设置邻居n的父节点为当前处理的node节点
processed.append(node) #标记为已处理
node = find_lowest_cost_node(costs) #找出接下来要处理的节点,重新开始循环
网友评论