我有以下功能程序。功能BFS显示从节点到目标/目标的路径。我可以修改功能BFS,以便不是将单个字符作为目标,而是 应该接受一个字符列表。
# tree stored as a dictionary (parent: [children])
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]#extracting the children of a node
for child in children:#i get the children using a for loop and yield
yield child
# Breadth-First search of a dictionary tree
def BFS(nodelist,target,dictionarytree):
print "Nodelist:",nodelist
childlist=[]
# iterate over all the nodes in parentlist
for parent in nodelist:
# if the node is the target
if parent[-1]==target:
return parent
# check if the node has children
if dictionarytree.has_key(parent[-1]):#check if the key exists in the dictionary
# loop through children and return children
for child in Successors(parent[-1],dictionarytree):
print child
childpath=parent+(child,)#add the targert to the childpath
childlist.append(childpath)
print "childpath",childpath
# if there are children, progress to the next level of the tree
if len(childlist) != 0:
return BFS(childlist,target,dictionarytree)
else:
return None
node='a'
goal='z'
print simpletree
print BFS([(node,)],goal,simpletree)
答案 0 :(得分:0)
嗯,BFS并没有真正设计为具有多个目标结尾。在周围的怪人之后你无法真正称之为BFS。如果您对此非常感兴趣,可以随时将其绘制出来,看看如果您在心理上遵循算法会发生什么。但是你需要跟踪哪个目标的路径。我认为它不会那么有用。
就个人而言,由于这看起来像是为了学校,我只是迭代另一个函数中的字符列表并存储值。您需要编辑BFS函数以返回路径而不是打印它。
def multipleBFSRuns(listOfChars):
values=[]
for x in listOfChars:
values.append(BFS([(node,)],x,simpletree))
return values