狄克斯特拉算法 Python

对下图路径用狄克斯特拉算法 Python 实现
在这里插入图片描述

算法的基本方法

在这里插入图片描述

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"] = {}

# the costs table
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity

# the parents table
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None

processed = []


def find_lowest_cost_node(costs):
    """
    传入参数 costs 表
    根据当时 costs 表的记录返回消耗最低的节点
    """
    lowest_cost = float("inf")
    lowest_cost_node = None

    # 遍历 costs 表中各节点,找出消耗最低的
    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:
    # 从 costs 表中获得该节点的消耗
    cost = costs[node] 
    # 从 graph 表得到该节点的相邻节点
    neighbors = graph[node] 

    # 再用一个循环,遍历该节点的相邻节点
    for n in neighbors.keys():
        # 新节点的消耗 = 父节点的消耗 + 父节点到新节点的权重
        new_cost = cost + neighbors[n]
        # 如果新节点消耗比原来低
        if costs[n] > new_cost:
            # 更新 costs 表
            costs[n] = new_cost
            # 更新 parents 表
            parents[n] = node
    # 把节点记录为已处理
    processed.append(node)
    # 找到下一个要处理的节点
    node = find_lowest_cost_node(costs)

# 最后把 costs 表和 parents 表打印出来
print(costs)
print(parents)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值