这几天在看<<算法图解>>这本书,在学到狄克斯特拉算法(找有向权重图的最短路径)的时候做练习题,算法基础不好所以还做了挺久的,下面是解答
# 将不知道的开销设置成无限大 infinity = 10000 # 第一个字典graph存储所有结点到相邻结点的权重 graph = dict() graph['start'] = {} graph['start']['A'] = 5 graph['start']['B'] = 2 graph['A'] = {} graph['A']['C'] = 2 graph['A']['D'] = 4 graph['B'] = {} graph['B']['A'] = 8 graph['B']['C'] = 7 graph['C'] = {} graph['C']['final'] = 1 graph['D'] = {} graph['D']['C'] = 6 graph['D']['final'] = 3 graph['final'] = {} # 第二个字典存放到各个结点的总权重并且会实时更新 costs = dict() costs['A'] = 5 costs['B'] = 2 costs['C'] = infinity costs['D'] = infinity costs['final'] = infinity # 第三个字典为存储父节点的散列表,便于最后找最短路径 parents = dict() parents['start'] = None parents['A'] = 'start' parents['B'] = 'start' parents['C'] = None parents['D'] = None parents['final'] = None # 创建数组处理记录过的结点. processed = [] # 创建寻找最低开销结点的函数 def find_lowest_cost_node(costs): lowest_cost = 10001 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 # 开始寻找最短路径 while True: node = find_lowest_cost_node(costs) if node is not None: cost = costs[node] neighbors = graph[node] for n in neighbors.keys(): new_cost = cost + neighbors[n] if new_cost < costs[n]: costs[n] = new_cost parents[n] = node processed.append(node) if node == find_lowest_cost_node(costs): break # 格式化打印最短路径 x = 'final' y = parents[x] road = ['final'] while y != None : road.append(y) x = y y = parents[x] print("最短路径为:", end='') for i in range(0, len(road) - 1): weizhi = len(road) - i - 1 print(road[weizhi], end='->') print("final") print("最短路径长度为 ", costs['final'])