狄克斯特拉算法,找出图中权重最小的路径
#!python
#coding=utf-8
"""
狄克特斯拉算法
有以下图:
start --6-->a
start --2-->b
a --1-->end
b --5-->end
b --3-->a
使用迪克斯特拉算法找出start-->end
权重最小的路径
"""
def build_graph():
graph = {}
graph["start"] = {"a": 6, "b": 2}
graph["a"] = {"end": 1}
graph["b"] = {"end": 5, "a": 3}
graph["end"] = {}
return graph
def dijkstra():
graph = build_graph()
# 无穷大
infinity = float("inf")
costs = {"a": 6, "b": 2, "end": infinity}
parents = {"a": "start", "b": "start", "end": None}
# 已处理过的节点
processed = []
# 找出开销最低的节点名称
node = find_lowest_cost(costs, processed)
while node is not None:
cost = costs[node]
# 找出邻居节点
neighbors = graph[node]
for key in neighbors.keys():
new_cost = cost + neighbors[key]
if costs[key] > new_cost:
costs[key] = new_cost
parents[key] = node
processed.append(node)
node = find_lowest_cost(costs, processed)
print(costs)
print(parents)
"""
找到权重最低的节点
"""
def find_lowest_cost(costs, processed):
# 最小权重,初始化设置成无穷大
lowest_cost = float("inf")
lowest_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_node = node
return lowest_node
dijkstra()