对下图路径用狄克斯特拉算法 Python 实现
算法的基本方法
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"] = {}
# the costs table
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
# the parents table
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
processed = []
def find_lowest_cost_node(costs):
"""
传入参数 costs 表
根据当时 costs 表的记录返回消耗最低的节点
"""
lowest_cost = float("inf")
lowest_cost_node = None
# 遍历 costs 表中各节点,找出消耗最低的
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:
# 从 costs 表中获得该节点的消耗
cost = costs[node]
# 从 graph 表得到该节点的相邻节点
neighbors = graph[node]
# 再用一个循环,遍历该节点的相邻节点
for n in neighbors.keys():
# 新节点的消耗 = 父节点的消耗 + 父节点到新节点的权重
new_cost = cost + neighbors[n]
# 如果新节点消耗比原来低
if costs[n] > new_cost:
# 更新 costs 表
costs[n] = new_cost
# 更新 parents 表
parents[n] = node
# 把节点记录为已处理
processed.append(node)
# 找到下一个要处理的节点
node = find_lowest_cost_node(costs)
# 最后把 costs 表和 parents 表打印出来
print(costs)
print(parents)