4.1 案例 - 寻找最短路径
4.1.1 例一
假设你希望从双子峰坐公交车去金门大桥,希望找出耗时最短的路线:
①使用图建立问题模型(
加权图
,注:
权重不能为负
)。
②使用狄克斯特拉算法解决问题。
狄克斯特拉算法解决问题的四个步骤:
1.找出最便宜的节点,即可在最短时间内前往的节点。2.对于该节点的邻居,检查是否有前往他们的更短路径,如果有,就更新其开销。3.重复这个过程,直到对图中的每个节点都这样做了。4.计算最终路径。
方案:
1、先看起点,A和B,选便宜的A,其他没有的先设置成正无穷
2、然后A下一步是E,E的父节点是A,开销是21+4=25
3、A的4处理过了打勾,然后B和E,B小,处理B,B到C,开销15min,父节点B,B到D,总开销18min,B到C,开销15,以此类推。。
4、最后再往回推父节点即可
4.1.2 例二
# the graph 界定图的结构,
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6 # start到A是6,散列表里面也可以包含散列表
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["fin"] = 1 # fin是finish
graph["b"] = {} # 节点初始值是空
graph["b"]["a"] =3
graph["b"]["fin"]=5
graph["fin"]={}
# the costs table 开销表
infinity = float("inf") # ∞
costs = {}
costs["a"] = 6 # a的最小值是6
costs["b"] = 2 # b的最小值是2
costs["fin"] = infinity # finish最小值是∞,初始状态
# the parents table 父节点
parents = {}
parents["a"] = "start" # a和b的父节点都是start,finish还没有
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] # 每个cost = costs[节点]
# 如果当前节点为,未处理的节点中开销最小的...、
# 意思是从A/B走完后,是走CD还是E,选开销最小的
# 初始processed是[],
if cost < lowest_cost and node not in processed:
# ...更新最小节点为当前节点
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node # 最重要的是返回节点
# 在没处理的节点中找出开销最小的节点,就是上面函数的return
node = find_lowest_cost_node(costs)
# 在所有节点都被处理后,while将结束循环
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
processed.append(node)
# 找出接下来要处理的节点
node = find_lowest_cost_node(costs)
print "Cost from the start to each node:"
print costs
#Cost from the start to each node:
{'a': 5, 'b': 2, 'fin': 6}