最短路径算法-狄克斯特拉算法(Dijkstra)python实现

迪杰斯特拉(Dijkstra)算法是典型最短路径算法,用于计算一个节点到其他节点的最短路径。它的主要特点是以起始点为中心向外层层扩展(广度优先遍历思想),直到扩展到终点为止。

基本思想

1.通过Dijkstra计算图G中的最短路径时,需要指定一个起点D(即从顶点D开始计算)。
2.此外,引进两个数组S和U。S的作用是记录已求出最短路径的顶点(以及相应的最短路径长度),而U则是记录还未求出最短路径的顶点(以及该顶点到起点D的距离)。
3.初始时,数组S中只有起点D;数组U中是除起点D之外的顶点,并且数组U中记录各顶点到起点D的距离。如果顶点与起点D不相邻,距离为无穷大。
4.然后,从数组U中找出路径最短的顶点K,并将其加入到数组S中;同时,从数组U中移除顶点K。接着,更新数组U中的各顶点到起点D的距离。
5.重复第4步操作,直到遍历完所有顶点。

迪杰斯特拉(Dijkstra)算法图解

以上图为例,来对迪杰斯特拉进行算法演示(以顶点D为起点)。
在这里插入图片描述

Python实现

图的权重如图所示

图的权重如图所示

# the graph
graph = {}
graph["start"] = {}
graph["start"]["a"] = 2
graph["start"]["b"] = 5

graph["a"] = {}
graph["a"]["b"] = 8
graph["a"]["c"] = 7

graph["b"] = {}
graph["b"]["d"] = 4
graph["b"]["c"] = 2

graph["c"] = {}
graph["c"]["fin"] = 1

graph["d"] = {}
graph["d"]["c"] = 6
graph["d"]["fin"] = 3

graph["fin"] = {}

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

# the parents table
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["c"] = "start"
parents["d"] = "start"
parents["fin"] = 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 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)

print("cost from the start to each node:")
print(costs)
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值