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
def dijkstra(costs):
#在未处理的节点中找出开销最小的节点
node = find_lowest_cost_node(costs)
#这个while循环在所有节点都被处理过后结束
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)
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
# print(graph.values())
# print(graph.keys())
# print(graph.items())
# print(graph)
# print()
# print(graph["start"].values())
# print(graph["start"].keys())
# print(graph["start"].items())
# print(graph["start"])
# print(graph["start"]["a"])
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
print("{}:{}".format("initial graph",graph))
infinity = float("inf")
#创建开销表
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity
print("{}:{}".format("initial costs",costs))
#创建存储父节点的散列表
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
print("{}:{}".format("initial parents",parents))
#记录处理过的节点
processed = []
dijkstra(costs)
print()
print("{}:{}".format("finial costs",costs))
print("{}:{}".format("finial parents",parents))
运行结果:
initial graph:{'start': {'a': 6, 'b': 2}, 'a': {'fin': 1}, 'b': {'a': 3, 'fin': 5}, 'fin': {}}
initial costs:{'a': 6, 'b': 2, 'fin': inf}
initial parents:{'a': 'start', 'b': 'start', 'fin': None}
finial costs:{'a': 5, 'b': 2, 'fin': 6}
finial parents:{'a': 'b', 'b': 'start', 'fin': 'a'}