狄克斯特拉算法

广度优先算法,它找出的是段数最少的路径(无向图)。如果我们要找出最快的路径(加权图),可以使用狄克斯特拉算法。

狄克斯特拉算法包含四个步骤:
1.找出"最便宜"的节点,即可在最短时间内到达的节点
2.更新该节点的邻居的开销
3.重复这个过程,直到对图中的每个节点都这样做了
4.计算最终路径

以下图为例 实现狄克斯特拉算法(从起点到终点的最短路径)
在这里插入图片描述

要编写解决这个问题的代码,需要三个字典(散列表),分别是 GRAPH(图表),COSTS(开销表),PARENTS(路径表)

第一步 实现图

graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

graph["a"] = {}
graph["a"]["end"] = 1

graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["end"] = 5

graph["end"] = {}

第二步 实现开销表

infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["end"] = infinity

第三步 实现路径表

parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["end"] = None

随着算法的进行,我们将不断更新散列表costs和parents。
整体代码如下

""""
    graph = {
        'start': {'a': 6, 'b': 2}
            'a': {'end': 1}
            'b': { 'a':3 , 'end':5}
          'end': {}
    }
"""
# 图的实现
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

graph["a"] = {}
graph["a"]["end"] = 1

graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["end"] = 5

graph["end"] = {}

# 创建开销表costs
# 设置无穷大
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["end"] = infinity

# 创建存储父节点的路径表
parents = {}
parents["a"] = "start"
parents["b"] = "start"
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循环在所有节点被处理完后退出
def find_lowest_way(node):
    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)
    return costs

print(find_lowest_way(node))
print(parents)

注意
1 .仅当权重为正时,狄克斯特拉算法才管用
2.如果图中包含负权边,请使用贝尔曼-福德算法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值