狄克斯特拉算法找出的是总权重最小的路径
术语介绍:
狄克斯特拉算法用于每条边都有关联数字的图,这些数字称为权重。
带权重的图称为加权图,不带权重的图称为非加权图。
计算非加权图的最短路径,可使用广度优先搜索。要计算加权图中的最短路径,可使用狄克斯特拉算法。
不能将狄克斯特拉算法用于包含负权边的图。
#实现
graph = {}
graph["you"] = ["alice","bob","claire"]
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"] = 2
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 = Nonefor node in costs:cost = costs[node]if cost < lowest_cost and node not in processed:lowest_cost = costlowest_cost_node = nodereturn 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_costparents[n] = nodeprocessed.append(node)node = find_lowest_cost_node(costs)