我最近开始使用Python(3.5)进行编程,我正在尝试用Python解决一个简单的广度优先搜索问题(参见代码)
import queue
import networkx as nx
def bfs(graph, start, target):
frontier = queue.Queue()
frontier.put(start)
explored = list()
while not frontier.empty():
state = frontier.get()
explored.append(state)
print(explored)
if state == target:
return 'success'
print(graph.neighbors(state))
for neighbor in graph.neighbors(state):
if neighbor not in explored:
frontier.put(state)
return 'Failure to find path'
代码返回一个无限循环,似乎frontier.get()不会从队列中删除该项。这使得while循环无限,因为队列中的第一个值始终是函数输入中定义的起始节点。变量状态在每个while循环中都是相同的(始终是起始节点)。
我做错了什么?从我的理解,队列应该从起始节点移动到起始节点的邻居,因此不应该发生循环。
答案 0 :(得分:0)
因为您再次将state
值放入队列中。改变这个:
for neighbor in graph.neighbors(state):
if neighbor not in explored:
frontier.put(state) # Here you put the 'state' back!
到此:
for neighbor in graph.neighbors(state):
if neighbor not in explored:
frontier.put(neighbor) # Put in the neighbours instead.
答案 1 :(得分:0)
两件事。首先,我假设从SELECT statement
开始的所有内容都应该缩进一个级别。
如果我正确地读取你的算法,我相信错误是在返回之前的最后一行。你有:
while
只是插入您正在查看的节点。我认为你应该做的是:
frontier.put(state)
以便您浏览frontier.put(neighbor)
的所有直接邻居。否则你只是一遍又一遍地看着起始节点。