defsearch(src, des): """ 寻找从src到des之间的最短中转方案 :param src: 起点 :param des: 终点 :return: 路径(列表),中转数(整型) """ search_queue = deque() searched = [] level = 0 if src notin searched: searched.append(src) search_queue.append(src) while search_queue: vex = search_queue.popleft() level += 1 for v in graph[vex].keys(): if v notin searched: searched.append(v) search_queue.append(v) if graph[vex][v] isNoneor graph[vex][v] < level: parents[v] = vex graph[vex][v] = level #print(parents) stack = [] road = [] stack.append(des) child = des whilenot parents[child] isNone: stack.append(parents[child]) child = parents[child] while stack: road.append(stack.pop())
node = src i = 1 while des notin graph[node].keys(): node = road[i] i += 1 cost = graph[node][des]
return road, cost
defbfs_traverse(): """ 广度优先遍历图中的顶点 :return:无 """ search_queue = deque() searched = [] vexs = list(graph.keys()) for i in range(len(graph)): ifnot vexs[i] in searched: searched.append(vexs[i]) search_queue.append(vexs[i]) while search_queue: vex = search_queue.popleft() print(vex) for v in graph[vex].keys(): # 修改!!! if v notin searched: searched.append(v) search_queue.append(v)
# bfs_traverse()
r, c = search("A", 'E') print("最少中转次数为{},路径为{}".format(c, ','.join(r)))