zoukankan      html  css  js  c++  java
  • 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())
    
  • 相关阅读:
    C++ 虚函数表解析
    函数调用运算符重载
    成员访问运算符重载
    递增和递减运算符重载
    java 如何查看jdk版本&位数
    oracle 11g完美卸载
    win10 你没有足够的权限执行此操作。
    maven 找不到或无法加载主类
    eclipse 如何对maven项目进行打包?
    Core Dataeasy出现的错误
  • 原文地址:https://www.cnblogs.com/fredkeke/p/9233661.html
Copyright © 2011-2022 走看看