狄克斯特拉算法适用于都是正权边的加权图,求解最短路径。
步骤:
1、找出“最便宜”的节点,即可在最短时间内到达的节点
2、更新该节点的邻居的开销
3、重复这个过程,直到对图中的每个节点都这样做了
4、计算最终路径
要编写解决这个问题的代码,需要三个散列表:
随着算法的进行,你将不断更新列表costs和parents。
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"] = {}
infinity = float("inf") #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] #这个while循环在所有节点都被处理过后结束
neighbors = graph[node]
for n in neighbors.keys(): #遍历当前节点的所有邻居
new_cost = cost + neighbors[n]
if costs[n] > new_cost: #如果当前节点前往该邻居更近
costs[n] = new_cost #就更新该邻居的开销
parents[n] = node #同时将该邻居的父节点设置为当前节点
processed.append(node) #将当前节点标记为处理过
node = find_lowest_cost_node(costs) #找出接下来要处理的节点,并循环
print(costs["fin"])