狄克斯特拉算法用于在加权图中查找最短路径。
仅当权重为时算法才管用,如果图中包含负权边,请使用贝尔曼-福得算法。
# 有向无环图 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"] = {} # 开销表,节点的开销指的是从起点出发前往该节点需要多长时间 infinity = float("inf") # 表示无穷大 costs = {} costs["a"] = 6 costs["b"] = 2 costs["fin"] = infinity # 存储父节点的散列表 parents = {} parents["a"] = "start" parents["b"] = "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 and 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) # 找出接下来要处理的节点,并循环
原文地址:https://www.cnblogs.com/lt1548748657/p/12620030.html
时间: 2024-10-09 02:45:33