总结《算法图解》第7章

狄克斯特拉算法

主要思想是:
1、找出最便宜的节点,在最短时间内前往的节点,建立一个costs图和parents图,也就是出发点到各点的距离和父子节点关系图。
2、根据第一步找得到的节点,找到其邻居节点,更新经过第一步找到点的costs图和已该节点为父节点的parents图。
3、重复以上两个过程,直到图中所有点都已经做过了以上循环。
4、计算最终路径。

# 狄克斯特拉算法适用于有向无环图,不包含负权边
# 用散列表(Python 里面的字典)描述该图
graph = {}
graph['s'] = {}
graph['s']['a'] = 6
graph['s']['b'] = 2
graph['a'] = {}
graph['a']['d'] = 1
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['d'] = 5
graph['d'] = {}

# 用散列表描述花销
infinity = float('+inf')
costs = {}
costs['a'] = 6
costs['b'] = 2
costs['d'] = infinity

# 用散列表来描述父节点
parents = {}
parents['a'] = 's'
parents['b'] = 's'
parents['d'] = None

processed = []

# 找到花销里面最小的节点
def lowest_cost(costs):
    smallest = float('inf')
    lowest_node = None
    for node in costs:  # 在python字典里面,node就代表了key,用cost[key]就可以表达key对应的value
        cost = costs[node]
        if cost < smallest and node not in processed:
            smallest = cost
            lowest_node = node
    return lowest_node

# 更新花销节点和父节点

name = lowest_cost(costs)
print(name)
while name is not None:  # 字典里面的key不是空,代表还有节点
    for n in graph[name].keys():
        new_costs = costs[name] + graph[name][n]# 通过cost['b'] = 2,加上graph['b']['a'] = 3 ,graph['b']['d'] = 5就可以得到新的cost表
        if new_costs < costs[n]:
            costs[n] = new_costs
            parents[n] = name
    processed.append(name)
    name = lowest_cost(costs)
    print(costs)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值