这里给出一个广度优先算法的简单实例,得到的是关系最近的人。
首先,广度优先搜索可回答两类问题:
第一类问题:从A点出发,有没有前往B点的路径?
第二类问题:从A点出发,前往B点的哪条路径最短?
实例:假设你经营一个芒果农场,需要寻找芒果销售商,以便将芒果卖给他,为此你可以在朋友中查找!如果朋友中没有芒果销售商,那么你可以在朋友的朋友中查找!算法如下。。
朋友关系网络
# coding=utf-8
from collections import deque
def person_is_seller(name):
return name[-1] == 'm' # 判断是否是以'm'结尾
graph = {} # 此处的排序是按照图的关系排序的
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggm"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
def search(name):
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] # 添加新的联系人到待检查的队列中
print 'search_queue:',search_queue
searched.append(person) #添加检查过的人到列表中
print 'searched:',searched
return False # 整个while循环之后,还没有找到就返回False
search("you")
运行结果:
>>>
====== RESTART: C:\Users\LiLong\Desktop\Algorithm\search_algorithms.py ======
search_queue: deque(['bob', 'claire', 'peggy'])
searched: ['alice']
search_queue: deque(['claire', 'peggy', 'anuj', 'peggm'])
searched: ['alice', 'bob']
search_queue: deque(['peggy', 'anuj', 'peggm', 'thom', 'jonny'])
searched: ['alice', 'bob', 'claire']
search_queue: deque(['anuj', 'peggm', 'thom', 'jonny'])
searched: ['alice', 'bob', 'claire', 'peggy']
search_queue: deque(['peggm', 'thom', 'jonny'])
searched: ['alice', 'bob', 'claire', 'peggy', 'anuj']
peggm is a mango seller!
>>>
可以看到搜索到了要求的目标,并且是关系最近的一个,这里用到的图是最简单的,无权值的有向图。
其中的散列表的排序是按照图的关系排序的: