谈谈我理解的狄克斯特拉算法

狄克斯特拉算法(Dijkstra’s algorithm)

谈谈我理解的狄克斯特拉算法_第1张图片
图上每条边的一些数字,把这些数字叫做这条边的权值,可以认为是生活中两地之间坐公交车的费用,我们现在用狄克斯特拉算法算出从A地到B地的最便宜的公交路线。

思路如下:
第一步:找出最便宜的节点
第二步:找出该节点的邻居,检查是否存在前往它们的更便宜的路径,如果有,更新这个节点的开销(就是“钱”)(定义开销为起点到这个点所花的“钱”)
第三步:重复这个过程,直到图中每个节点都是“最便宜的”。
第四步:计算并给出最终路径

代码分块以及解释:
1、先来实现将图中的关系存到散列表中

graph = {}     #graph包含的是ABCDEF这六个节点
graph["a"] = {} #graph["a"]是graph的元素,也是一个字典,
                #里面存储这个节点到其他节点的价钱
graph["a"]["c"] = 5  #A到C要5元钱
graph["a"]["e"] = 2

graph["c"] = {}
graph["c"]["d"] = 4
graph["c"]["f"] = 2

graph["e"] = {}
graph["e"]["c"] = 8
graph["e"]["f"] = 7

graph["d"] = {}
graph["d"]["b"] = 3
graph["d"]["f"] = 6

graph["f"] = {}
graph["f"]["b"] = 1

graph["b"] = {}    

2、把每个节点的开销整合到一个散列表costs里面,方便后面更新开销:

costs = {}
costs["c"] = 5
costs["e"] = 2
costs["d"] = float("inf")
costs["f"] = float("inf")
costs["fin"] = float("inf")  # float("inf")表示无穷大 

3、把每个节点的父节点整合到parents散列表里面,方便后面更新,整合路径:

parents = {}
parents["c"] = "a"
parents["e"] = "a"
parents["d"] = None 
parents["f"] = None 
parents["b"] = None  

4、准备工作做完了,

graph = {}     #graph包含的是ABCDEF这六个节点
graph["a"] = {} #graph["a"]是graph的元素,也是一个字典,里面存储这个节点到其他节点的价钱
graph["a"]["c"] = 5  #A到C要5元钱
graph["a"]["e"] = 2

graph["c"] = {}
graph["c"]["d"] = 4
graph["c"]["f"] = 2

graph["e"] = {}
graph["e"]["c"] = 8
graph["e"]["f"] = 7

graph["d"] = {}
graph["d"]["b"] = 3
graph["d"]["f"] = 6

graph["f"] = {}
graph["f"]["b"] = 1

graph["b"] = {}

costs = {}
costs["c"] = 5
costs["e"] = 2
costs["d"] = float("inf")
costs["f"] = float("inf")
costs["b"] = float("inf")  # float("inf")表示无穷大

parents = {}
parents["c"] = "a"
parents["e"] = "a"
parents["d"] = None
parents["f"] = None
parents["b"] = None            #parents是表示每个节点的父节点

processed = []    #空列表用来存储已经处理过的节点
road = ['b']

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]
    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("Cost from the start to each node:")
print(costs)
print("The cheapest road is:")
temp = 'b'
while True:
    if temp is not 'a':
        road.append(parents[temp])
        temp = parents[temp]
    else:
        break
print(road[::-1])


其输出结果如下:
在这里插入图片描述
路线acfb就是最便宜的路径,b的开销为8,即最便宜到达需要“8元钱”。

文中思想和部分代码参考《算法图解》美Aditya Bhargava,如有侵权私信删。

你可能感兴趣的:(python,算法,编程语言)