python -- 广度优先搜索

来源:互联网 发布:淘宝商品不合格违规了 编辑:程序博客网 时间:2024/06/05 15:07
#! /usr/bin/env python3# -*- coding: utf-8 -*-from collections import dequegraph = {}graph['A'] = ['B', 'F']graph['B'] = ['C']graph['C'] = ['D']graph['F'] = ['E', 'G']graph['E'] = ['C']#graph['E'] = []graph['G'] = ['C']graph['D'] = []def broadsearch(start, target):search_queue = deque()search_queue += graph[start]got = Falsesearched = []while search_queue:node = search_queue.popleft()if node not in searched:print(node)if node == target:#print("Found it!")got = Trueelse:search_queue += graph[node]searched.append(node)print("Process is" + str(searched))return gotif __name__ == "__main__":getprocess = broadsearch('A', 'D')if getprocess:print("Found it")else:print("Not Found it")

ps:

广度优先搜索用于在非加权图中查找最短路径。
Dijkstra狄克斯特拉算法用于在加权图中查找最短路径。仅当权重为正时狄克斯特拉算法才管用。
如果图中包含负权边,请使用贝尔曼-福德算法。