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

# author: Jingke
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"] = {} # {'start': {'a': 6, 'b': 2}, 'a': {'fin': 1}, 'b': {'a': 3, 'fin': 5}}
# print(graph['start']) #{'a': 6, 'b': 2}
infinity = float("inf")
parent = {}
parent['a'] = 'start'
parent['b'] = 'start'
parent['fin'] = None # {'a': 'start', 'b': 'start', 'fin': None}
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity # {'a': 6, 'b': 2, 'fin': inf}
def lowest_node(costs, proceed):
lowest_cost = float("inf")
lowest_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in proceed:
lowest_node = node
lowest_cost = cost
return lowest_node
def dijkstra(costs, parent, graph):
proceed = []
lowest_nod = lowest_node(costs, proceed)
while lowest_nod:
lowest_cost = costs[lowest_nod]
neighbor = graph[lowest_nod]
for neighbor_node in neighbor.keys():
new_cost = lowest_cost + neighbor[neighbor_node]
if new_cost < costs[neighbor_node]:
costs[neighbor_node] = new_cost
parent[neighbor_node] = lowest_nod
proceed.append(lowest_nod)
lowest_nod = lowest_node(costs, proceed)
return costs, parent
costs, parent = dijkstra(costs, parent, graph)
print(costs) #{'a': 5, 'b': 2, 'fin': 6}
print(parent) #{'a': 'b', 'b': 'start', 'fin': 'a'}
网友评论