广度优先算法,它找出的是段数最少的路径(无向图)。如果我们要找出最快的路径(加权图),可以使用狄克斯特拉算法。
狄克斯特拉算法包含四个步骤:
1.找出"最便宜"的节点,即可在最短时间内到达的节点
2.更新该节点的邻居的开销
3.重复这个过程,直到对图中的每个节点都这样做了
4.计算最终路径
以下图为例 实现狄克斯特拉算法(从起点到终点的最短路径)
要编写解决这个问题的代码,需要三个字典(散列表),分别是 GRAPH(图表),COSTS(开销表),PARENTS(路径表)
第一步 实现图
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["end"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["end"] = 5
graph["end"] = {}
第二步 实现开销表
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["end"] = infinity
第三步 实现路径表
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["end"] = None
随着算法的进行,我们将不断更新散列表costs和parents。
整体代码如下
""""
graph = {
'start': {'a': 6, 'b': 2}
'a': {'end': 1}
'b': { 'a':3 , 'end':5}
'end': {}
}
"""
# 图的实现
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["end"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["end"] = 5
graph["end"] = {}
# 创建开销表costs
# 设置无穷大
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["end"] = infinity
# 创建存储父节点的路径表
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["end"] = 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循环在所有节点被处理完后退出
def find_lowest_way(node):
while node is not None:
cost = costs[node]
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)
return costs
print(find_lowest_way(node))
print(parents)
注意
1 .仅当权重为正时,狄克斯特拉算法才管用
2.如果图中包含负权边,请使用贝尔曼-福德算法