2018-05-07

今天学习狄克斯特拉算法,为了尊敬发明人,必须用他的名字
dijkstra's algorithm ,dijkstra's algorithm,dijkstra's algorithm 三遍表示尊敬。
再次,感谢 https://blog.csdn.net/sgs595595/article/details/79018202
几乎所有的代码,来自这里
(希望您看到我引用您的代码,能高兴,)

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"] = {}
# costs
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
# parent
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
# processe
processed = []

#find_lowest
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


#Dijkstra implement
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(processed)

#  now ,i add some code ,to print the lowest way 
theway=[]   # create a new list for print the lowest way
print(parents["fin"] )  
hh=1    # to Avoid dead loops

lala = parents["fin"]   # for debug 
theway.append("fin")   
theway.append(lala)
while lala != "start" and hh<500: # to Avoid dead loops
    lala =parents[lala]
    #print(lala)   # for debug
    hh+=7
    #print(hh)  # for debug 
    theway.append(lala)
theway.reverse()   # reverse it ,
print(theway)  # so now ,there is the way

感谢 https://www.tutorialspoint.com/execute_python_online.php
直接在这里运行,连环境都不用自己搭建。
感谢。
希望对您有点帮助。

运行结果如下 。

$python main.py
a
b
start
['start', 'b', 'a', 'fin']

感谢 算法图解 作者 Aditya Bhargava , 译者 袁国忠 。
最后,推荐,手机一定要装的软件是,得到,得到,得到。

你可能感兴趣的:(2018-05-07)