学习笔记 | Dijkstra单源最短路

Dijkstra算法

在这里插入图片描述

代码实现

# 迪克斯特拉算法: 计算加权图中的最短路径
# graph: 起点start,a,b,终点fin之间的距离

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

# costs: 起点到 a,b,fin的开销
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity

# parents: 存储父节点,记录最短路径
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None

# processed: 记录处理过的节点,避免重复处理
processed = []

# find_lowest_cost_node(costs): 返回开销最低的点
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

# Dijkstra implement
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)

tmp = "fin"
path = ["fin"]
while parents[tmp] != "start":
    path.append(parents[tmp])
    tmp = parents[tmp]
    
path.append("start")
for i in range(0,len(path)):
    print(path[len(path)-i-1])

输出:
在这里插入图片描述

步骤

Dijkstra算法包含4个步骤:
(1) 找出最便宜的节点,即可在最短时间内前往的节点。
(2) 对于该节点的邻居,检查是否有前往它们的更短路径,如果有,就更新其开销。 (3) 重复这个过程,直到对图中的每个节点都这样做了。
(4) 计算最终路径。

注意

  • 不能将Dijkstra算法用于包含负权边的图。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章