《算法图解》之广度优先搜索实现图结构的最短路径搜索

这个思路不错的。

用python的字典实现有向图,

然后用双向队列deque控制队列的进出方向。

现在可能用得少,但说不定以后呢?:)

《算法图解》之广度优先搜索实现图结构的最短路径搜索_第1张图片

 

from collections import deque

graph = dict()
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph['alice'] = ["peggy"]
graph["claire"] = ["thom", "johnny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["johnny"] = []


def person_is_seller(name):
    return name[-1] == "b"


def search(name):
    search_queue = deque()
    search_queue += graph[name]
    searched = []
    while search_queue:
        person = search_queue.popleft()
        if person not in searched:
            if person_is_seller(person):
                print(person + " is a mango seller!")
                return True
            else:
                search_queue += graph[person]
                searched.append(person)
    return False


search("you")

 

转载于:https://www.cnblogs.com/aguncn/p/9341705.html

你可能感兴趣的:(《算法图解》之广度优先搜索实现图结构的最短路径搜索)