• python代码实现dijkstra算法


    求解从1到6的最短路径。

    python代码实现:(以A-F代表1-6)

    # Dijkstra算法需要三张散列表和一个存储列表用于记录处理过的节点,如下:
    processed = []
    
    def build_graph():
        """建立图关系的散列表"""
        graph = {}
        graph["A"] = {}
        graph["A"]["B"] = 1
        graph["A"]["C"] = 12
        graph["B"] = {}
        graph["B"]["C"] = 9
        graph["B"]["D"] = 3
        graph["C"] = {}
        graph["C"]["E"] = 5
        graph["D"] = {}
        graph["D"]["E"] = 13
        graph["D"]["F"] = 15
        graph["D"]["C"] = 4
        graph["E"] = {}
        graph["E"]["F"] = 4
        graph["F"] = {}
        return graph
    
    
    def build_costs():
        """建立开销的散列表"""
        infinity = float("inf")    # 无穷大
        costs = {}
        costs["B"] = 1
        costs["C"] = 12
        costs["D"] = infinity
        costs["E"] = infinity
        costs["F"] = infinity
        return costs
    
    
    def build_parents():
        """建立存储父节点的散列表"""
        parents = {}
        parents["B"] = "A"
        parents["C"] = "A"
        parents["D"] = None
        parents["E"] = None
        parents["F"] = None
        return parents
    
    
    # 下面是正式的算法步骤
    def find_low_cost_node(costs):
        """首先要在未处理的节点找出开销最小的节点,在(开销表)中找,如果没有或者全部都已经处理过了,返回初始值None"""
        lowest_cost = float("inf")
        lowest_cost_node = None
        for node,cost in costs.items():
            if cost < lowest_cost and node not in processed:
                lowest_cost = cost
                lowest_cost_node = node
        return lowest_cost_node
    
    
    def solve_shortest_route(graph,costs,parents):
        """dijkstra算法求解"""
        node = find_low_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_low_cost_node(costs)
    
        # 输出结果:
        print("graph:",graph)
        print("costs:",costs)
        print("parents:",parents)
    
    
    if __name__ == '__main__':
        solve_shortest_route(build_graph(),build_costs(),build_parents())
  • 相关阅读:
    node-webkit 不支持html5_video播放mp4的解决方法
    node-webkit(Windows系统) 打包成exe文件后,被360杀毒软件误报木马的解决方法
    剑指 Offer 36. 二叉搜索树与双向链表
    剑指 Offer 33. 二叉搜索树的后序遍历序列
    Leetcode96. 不同的二叉搜索树
    Leetcode95. 不同的二叉搜索树 II
    leetcode1493. 删掉一个元素以后全为 1 的最长子数组
    Leetcode1052. 爱生气的书店老板
    Leetcode92. 反转链表 II
    Leetcode495. 提莫攻击
  • 原文地址:https://www.cnblogs.com/chichung/p/10152307.html
Copyright © 2020-2023  润新知