Python DFS搜索未返回我的列表中的某些节点
我在DFS中使用此实现来获取我在函数中指定的根的节点,但是对于adjLists1,我在调用2作为根时使用了一个错误。1和3返回其子节点,但2不返回。不知道我做错了什么。 我得到的错误是:Python DFS搜索未返回我的列表中的某些节点,python,search,depth-first-search,Python,Search,Depth First Search,我在DFS中使用此实现来获取我在函数中指定的根的节点,但是对于adjLists1,我在调用2作为根时使用了一个错误。1和3返回其子节点,但2不返回。不知道我做错了什么。 我得到的错误是: Traceback (most recent call last): 2 5 File "DFS2.py", line 42, in <module> dfs_iterative(adjLists1, 2) File "DFS2.py", line 17, in dfs_iter
Traceback (most recent call last):
2 5 File "DFS2.py", line 42, in <module>
dfs_iterative(adjLists1, 2)
File "DFS2.py", line 17, in dfs_iterative
if(not visited[w]):
IndexError: list index out of range
您可以通过使用列表中的最大值来避免没有空白子节点的问题,并适当地防止索引: 您的代码也可以简化一点:
import itertools as it
def dfs_iterative(adjLists, s):
stack = [s]
n = len(adjLists)
visited = [False] * (max(it.chain(*adjLists))+1)
while stack:
v = stack.pop()
if visited[v]:
continue
visited[v] = True
print(v, " ", end='')
if v >= n: # Guard against trying to index with v
continue
for w in adjLists[v]:
stack.append(w)
>>> adjLists1 = [ [1,2,3], [4], [5,6], [7,8], [], [9,10,11], [12,13,14], [], []]
>>> dfs_iterative(adjLists1, 2)
2 6 14 13 12 5 11 10 9
注意:您从未索引过0,因此[1,2,3]从未被探索过。您的邻接列表包含9个元素(内部列表)。因此n等于9,您创建了一个长度为9的访问数组。但是,当您尝试从节点2启动DFS时,将转到5,6。然后您尝试探索6,这将引导您到节点12、13、14。您的访问列表中没有第14个元素。我现在明白了。我在列表中添加了空元素以将长度扩展到14,现在可以看到子节点。这不是一个很好的解决方案,但它现在可以工作了。谢谢
import itertools as it
def dfs_iterative(adjLists, s):
stack = [s]
n = len(adjLists)
visited = [False] * (max(it.chain(*adjLists))+1)
while stack:
v = stack.pop()
if visited[v]:
continue
visited[v] = True
print(v, " ", end='')
if v >= n: # Guard against trying to index with v
continue
for w in adjLists[v]:
stack.append(w)
>>> adjLists1 = [ [1,2,3], [4], [5,6], [7,8], [], [9,10,11], [12,13,14], [], []]
>>> dfs_iterative(adjLists1, 2)
2 6 14 13 12 5 11 10 9