Dijkstra’s algorithm
狄克斯特拉算法包含4个步骤
(1) 找出最便宜的节点,即可在最短时间内前往的节点。
(2) 对于该节点的邻居,检查是否有前往它们的更短路径,如果有,就更新其开销。
(3) 重复这个过程,直到对图中的每个节点都这样做了。
(4) 计算最终路径。
只适用于有向无环图
关键理念:找出图中最便宜的节点,并确保没有到该节点的更便宜的路径!
不能处理负权边
#节点之间的邻居关系,单向的
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["finish"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["finish"] = 5
#节点的消耗
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["finish"] = infinity
#保存父节点,路径图
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["finish"] = None
processed = []
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs:
if costs[node] < lowest_cost and node not in processed:
lowest_cost = costs[node]
lowest_cost_node = node
return lowest_cost_node
def find_path():
node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
if node not in graph:
processed.append(node)
node = find_lowest_cost_node(costs)
continue
neightbors = graph[node]
for n in neightbors.keys():
new_cost = cost + neightbors[n]
if new_cost < costs[n]:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
find_path()
print(parents)