非加权图中查找最短路径--广度优先搜索

2020-03-04  本文已影响0人  还是那个没头脑
from collections import deque

graph = {}
graph["you"] = ["小明","小红","小黄"]
graph["小明"] = []
graph["小红"] = []
graph["浅黄"] = []
graph["土黄"] = []
graph["深黄"] = []
graph["小黄"] = ["浅黄","土黄","深黄"]

def person_is_seller(name):
    return name[0] =='土'

def search(name):
    search_queue = deque()
    search_queue += graph[name]
    searchd = []
    while search_queue:
        person = search_queue.popleft()
        if person not in searchd:
            if person_is_seller(person):
                print(f'找到了{person}')
                return True
            else:
                search_queue += graph[person]
                searchd.append(person)
    return False

search("you")

运行时间O(人数+边数),通常写作O(V+E),V为顶点数,E为边数

上一篇下一篇

猜你喜欢

热点阅读