File tree Expand file tree Collapse file tree
AlgorithmDiagram9787115447630/chapter06/c06_5_BFS Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """ 广度搜索算法 """
2+ from collections import deque
3+
4+ """ 从你的社交关系网中找到芒果销售商:
5+ 01 你的社交关系:
6+
7+ /-ALICE -----> PEGGY
8+ / |
9+ / |-->
10+ You --------------------> BOB -----> ANUJ
11+ \
12+ \-----> CLAIRE -----> THOM
13+ \
14+ \
15+ \-----> JONNY
16+
17+ 02 目标芒果销售商:名字以M结尾
18+ """
19+
20+
21+ # 判断一个人是否是芒果销售商
22+ def person_is_seller (name ):
23+ return name [- 1 ] == 'm'
24+
25+
26+ # 查找芒果销售商的方法
27+ def search (name ):
28+ search_queue = deque ()
29+ search_queue += graph [name ]
30+ searched = [] # 这个数组用于记录检查过的人
31+ while search_queue :
32+ person = search_queue .popleft ()
33+ if person not in searched : # 仅当这个人没检查过时才检查
34+ if person_is_seller (person ):
35+ print (person + " is a mango seller!" )
36+ return True
37+ else :
38+ search_queue += graph [person ]
39+ searched .append (person ) # 将这个人标记为检查过
40+ return False
41+
42+
43+ # 初始化你的社交关系网
44+ graph = {
45+ "you" : ["alice" , "bob" , "claire" ],
46+ "bob" : ["anuj" , "peggy" ],
47+ "alice" : ["peggy" ],
48+ "claire" : ["thom" , "jonny" ],
49+ "anuj" : [],
50+ "peggy" : [],
51+ "thom" : [],
52+ "jonny" : []
53+ }
54+
55+ search ("you" )
You can’t perform that action at this time.
0 commit comments