我有一个如下所示的函数程序。BFS函数显示从节点到目标/目标的路径。我如何修改BFS函数,使其不接受单个字符作为目标,而是接受一个字符列表?
# 树存储为字典(父节点: [子节点])
simpletree = {'a': ['b', 'c'],
'b': ['d','e', 'f'],
'c': ['g', 'h', 'i','j'],
'd': ['k', 'l'],
'e': ['m'],
'g': ['n'],
'i': ['o'],
'j': ['p'],
'o': ['z']}
def Successors(node,dictionarytree):
children=dictionarytree[node]#提取节点的子节点
for child in children:#通过for循环获取子节点并yield
yield child
# 字典树的广度优先搜索
def BFS(nodelist,target,dictionarytree):
print "Nodelist:",nodelist
childlist=[]
# 遍历父节点列表中的所有节点
for parent in nodelist:
# 如果节点是目标
if parent[-1]==target:
return parent
# 检查节点是否有子节点
if dictionarytree.has_key(parent[-1]):#检查字典中是否存在该键
# 遍历子节点并返回子节点
for child in Successors(parent[-1],dictionarytree):
print child
childpath=parent+(child,)#将目标添加到子路径
childlist.append(childpath)
print "childpath",childpath
# 如果有子节点,继续到树的下一层
if len(childlist) != 0:
return BFS(childlist,target,dictionarytree)
else:
return None
node='a'
goal='z'
print simpletree
print BFS([(node,)],goal,simpletree)
回答:
嗯,BFS并不是真正设计用来处理多个目标结尾的。你在修改后也不能真正称之为BFS。如果你真的对这个感兴趣,你可以把它画出来,然后在脑海中按照算法进行模拟。但你需要跟踪哪个路径对应哪个目标。我认为这不会有太大帮助。
就我个人而言,既然这看起来是为学校准备的,我会建议在另一个函数中遍历字符列表并存储值。不过,你需要编辑你的BFS函数,使其返回路径而不是打印路径。
def multipleBFSRuns(listOfChars):
values=[]
for x in listOfChars:
values.append(BFS([(node,)],x,simpletree))
return values