狄克斯特拉算法

狄克斯特拉算法:解决了有向图最短路径的问题

狄克斯特拉算法包含4个步骤

(1) 找出“最便宜”的节点,即可在最短时间内到达的节点。

(2) 更新该节点的邻居的开销。

(3) 重复这个过程,直到对图中的每个节点都这样做了。

(4) 计算最终路径

image.png
# author: Jingke

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"] = {} # {'start': {'a': 6, 'b': 2}, 'a': {'fin': 1}, 'b': {'a': 3, 'fin': 5}}
# print(graph['start']) #{'a': 6, 'b': 2}

infinity = float("inf")
parent = {}
parent['a'] = 'start'
parent['b'] = 'start'
parent['fin'] = None # {'a': 'start', 'b': 'start', 'fin': None}

costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity  # {'a': 6, 'b': 2, 'fin': inf}

def lowest_node(costs, proceed):
    lowest_cost = float("inf")
    lowest_node = None
    for node in costs:
        cost = costs[node]
        if cost < lowest_cost and node not in proceed:
            lowest_node = node
            lowest_cost = cost
    return lowest_node


def dijkstra(costs, parent, graph):
    proceed = []
    lowest_nod = lowest_node(costs, proceed)
    while lowest_nod:
        lowest_cost = costs[lowest_nod]
        neighbor = graph[lowest_nod]
        for neighbor_node in neighbor.keys():
            new_cost = lowest_cost + neighbor[neighbor_node]
            if new_cost < costs[neighbor_node]:
                costs[neighbor_node] = new_cost
                parent[neighbor_node] = lowest_nod
        proceed.append(lowest_nod)
        lowest_nod = lowest_node(costs, proceed)
    return costs, parent

costs, parent = dijkstra(costs, parent, graph)
print(costs) #{'a': 5, 'b': 2, 'fin': 6} 
print(parent) #{'a': 'b', 'b': 'start', 'fin': 'a'}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容