while search_queue: ←------只要队列不为空 person = search_queue.popleft() ←------就取出其中的第一个人 if person_is_seller(person): ←------检查这个人是否是芒果销售商 print person + " is a mango seller!" ←------是芒果销售商 returnTrue else: search_queue += graph[person] ←------不是芒果销售商。将这个人的朋友都加入搜索队列 returnFalse ←------如果到达了这里,就说明队列中没人是芒果销售商
使用一个列表来记录检查过的人,这很重要。否则可能会陷入无限循环,实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defsearch(name): search_queue = deque() search_queue += graph[name] searched = [] ←------------------------------这个数组用于记录检查过的人 while search_queue: person = search_queue.popleft() if person notin searched: ←----------仅当这个人没检查过时才检查 if person_is_seller(person): print person + " is a mango seller!" returnTrue else: search_queue += graph[person] searched.append(person) ←------将这个人标记为检查过 returnFalse search("you")
广度优先搜索的运行时间为O (人数 + 边数),这通常写作O (V + E ),其中V 为顶点(vertice)数,E 为边数。