廣度優先搜索

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-11-30 18:02:21
# @Author  : rorg (928758777)
# @Link    : QQ:928758777
# @Version : $Id$

from collections import deque


def person_is_seller(name):
    # print(name[-1])
    return name[-1] == 'm'


def search(name):
    graph = {}
    graph['you'] = {'alice', 'bob', 'jack'}
    graph['alice'] = {}
    graph['bob'] = {}
    graph['jack'] = {'gm'}
    graph['mg'] = {}
    search_queue = deque()
    search_queue += graph[name]
    searched = []
    while search_queue:
        person = search_queue.popleft()
        if not person 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


print(search('you'))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章