相关信息
广度优先搜索学习
以下代码段摘录自算法图解中,可以很好的理解广度优先算法
python
def search(name):
search_queue = deque() # 创建队列用于 BFS
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 # 找到后返回 True
else:
search_queue += graph[person] # 将此人的邻居加入队列
searched.append(person) # 标记为已检查
return False # 队列为空仍未找到,返回 False
本文作者:曹子昂
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!