• Dijkstra Algorithm 迪克特斯拉算法--Python


    迪克斯拉特算法:

    1、找出代价最小的节点,即可在最短时间内到达的节点;

    2、更新节点的邻居的开销;

    3、重复这个过程,直到图中的每个节点都这样做了;

    4、计算最终路径。

    '''
    迪克斯特拉算法:
    1、以字典的方式更新图,包括权重
    2、创建开销字典,关键在于起点临近的点开销为实际数值,其他点为暂时未到达,开销为无穷,随后更新
    3、创建父节点列表保存每个点的父节点,以便记录走过的路径
    '''
    from queue import LifoQueue
    
    graph = {}
    graph['start'] = {}
    graph['start']['a'] = 6
    graph['start']['b'] = 2
    graph['a'] = {}
    graph['a']['end'] = 4
    graph['b'] = {}
    graph['b']['a'] = 3
    graph['b']['c'] = 2
    graph['c'] = {}
    graph['c']['end'] = 3
    graph['end'] = {}
    print(graph)
    
    infinity = float('inf')
    costs = {}
    costs['a'] = 6
    costs['b'] = 2
    costs['c'] = infinity
    costs['end'] = infinity
    
    parents = {}
    parents['a'] = 'start'
    parents['b'] = 'start'
    parents['c'] = 'b'
    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(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)
    
    #输出最短路径
    p = 'end'
    path = LifoQueue()
    while(True):
        path.put(p)
        if(p == 'start'):
            break
        p = parents[p]
    
    while not path.empty():
        print(path.get())
    
  • 相关阅读:
    【项目】项目225
    【原创】如何带格式转载博客园文章或其他网站的文章
    【项目】项目226
    【项目】项目229
    【项目】项目223
    【项目】项目230
    【项目】项目227
    如何带格式转载博客园文章或其他网站的文章
    Thread.Sleep(0)真的是bug吗?
    14.redis的慢日志
  • 原文地址:https://www.cnblogs.com/fredkeke/p/9233661.html
Copyright © 2020-2023  润新知