python实现广度优先搜索

思路:用字典来实现图,key值为节点,每个key对应的value值为一个队列,存储该节点的所有邻居节点。

# 广度优先搜索
from collections import deque
def research ():
    # 字典模拟图结构,假设从“you”出发,朋友关系网里找卖家,没有就在朋友的朋友的关系网里找。。。
    graph = dict ()
    graph[ "you" ] = [ "alice" , "bob" , "claire" ]
    graph[ "bob" ] = [ "anuj" , "peggy" ]
    graph[ "alice" ] = [ "peggy" ]
    graph[ "claire" ] = [ "thom" , "jonny" ]
    graph[ "anuj" ] = []
    graph[ "peggy" ] = []
    graph[ "thom" ] = []
    graph[ "jonny" ] = []
    # 创建一个队列,将首节点的邻居加入搜索队列
    que = deque()
    que += graph[ "you" ]
    # 用于标记是否被检查
    researched = []
    while que:
        # 队列不为空,取出第一个人
        person = que.popleft()
        if person not in researched:
            if person_is_seller(person):
                print (person + " is a seller" )
                return True
            else :
                # 当前搜索的人不是卖家,添加进已检查队列
                researched.append(person)
                que += graph[person]
    return False
def person_is_seller ( name ):
    # 假设名字最后一个字母为m的人就是卖家
    return name[ - 1 ] == "m"

你可能感兴趣的:(python实现广度优先搜索)