狄克斯特拉算法
一、引言
在广度优先搜索算法中我们所找的路径可能是段数最少,但是时间却不一定是最短的,就拿下面这个例子来说
红色标记的是用广度优先搜索算法得到的最短路径,那么假如我们在上面赋予权重,也就是加上时间呢?
那么还是原来的路线最短吗?
答案是否定的,如果加上权重的话,应该是上面标红的路线最短,要找出这条路线,我们就要用到狄克斯特算法。
二、算法的操作步骤
狄克斯特算法大致分为以下步骤:
- 找出最权重最小的点,也就是我们从家出发,到那个位置,所花费的时间最短。
- 计算该节点前往各个邻居节点所花费的时间。
- 重复前面的过程
- 到达学校(终点)
- 然后沿着父节点进行溯源,这样就可以得到时间最短路径
三、算法实现
#记录了每个节点的邻居和前往邻居所花费的时间。f代表终点,s代表起点
graph = {}
graph['s'] = {}
graph['s']['a'] = 5
graph['s']['b'] = 2
graph['a'] = {}
graph['a']['c'] = 4
graph['a']['d'] = 2
graph['b'] = {}
graph['b']['a'] = 8
graph['b']['d'] = 7
graph['c'] = {}
graph['c']['d'] = 6
graph['c']['f'] = 3
graph['d'] = {}
graph['d']['f'] = 1
graph['f']={}
#记录从起点到每个节点所花费的时间,无法确定的计作无穷大
infinit = float('inf')
costs = {}
costs['a']= 5
costs['b'] = 2
costs['c']=infinit
costs['d']=infinit
costs['f']=infinit
#第三个散列表用于记录 每个节点的父节点
parents = {}
parents['a'] = 's'
parents['b'] = 's'
parents['f'] = None
#计算时,将不断更新 costs和parents散列表 ,并将处理过的节点记录在该数组
processed = []
#查找当前离起点最近的一个未处理的节点
def find_lowerest_node(costs):
lowerst_cost = float('inf')
lowerst_cost_node = None
for node in costs:
if costs[node] < lowerst_cost and node not in processed:
lowerst_cost = costs[node]
lowerst_cost_node = node
return lowerst_cost_node
node = find_lowerest_node(costs)
#只要还有未处理的节点,就循环处理
while node is not None:
cost = costs[node]
#对于该节点的邻居,检查是否有前往它们的更短路径,如果有,就更新其开销。并更新父节点为该节点。
neighbors = graph[node]
for n in neighbors:
new_costs = cost + neighbors[n]
if new_costs < costs[n]:
costs[n] = new_costs
parents[n] = node
processed.append(node)
node = find_lowerest_node(costs)
print(costs)
四、适用场景
计算加权图中的最短路径可以使用狄克斯特拉算法,但是图中不能存在环,以及负权变,如果要计算带有负权边的图,那么就要使用贝尔曼-福特算法。
参考资料:算法图解