我正在尝试对算法进行编码,以通过广度优先搜索找到从一个节点s
到另一个节点f
的最佳路径。我发现了以下代码,我几乎完全理解了这一切,但我不知道他们在这行中做了什么:
while frontier: ...
我的问题是
以下是代码:
Graph_Adjs={'s':['a','x'],'a':['s','z'],'x':['s','d','c'],'z':['a'],'d':['x','c','f'], 'c':['d','x','f','v'],'f':['d','c','v'],'v':['f','c'] }
def BFS (Graph_Adjs,s='s'):
level = {'s':0}
father = {'s':None}
i = 1
frontier = [s]
while frontier:
next = []
for u in frontier:
for v in Graph_Adjs[u]:
if v not in level:
level[v] = i
father[v] = u
next.append(v)
frontier = next
i+=1
return father
if __name__=='__main__':
father = BFS (Graph_Adjs,s='s')
f = 'f'
path = []
while f !=None:
path.append(f)
f = father[f]
path.reverse()
print (path)
答案 0 :(得分:1)
在Python中,如果列表的真值非空,则为真,否则为假。该条件有效地实现了一种记录被访问节点的方法,因此它们不会再次迭代。