我在DFS中使用此实现来获取我在函数中指定的根节点,但是对于adjLists1我使用I时出错,当我将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_iterative
if(not visited[w]):
IndexError: list index out of range
程序:
def dfs_iterative(adjLists, s):
stack = []
stack.append(s)
n = len(adjLists)
visited = []
for i in range(0,n):
visited.append(False)
while(len(stack)>0):
v = stack.pop()
if(not visited[v]):
visited[v] = True
print(v, " ", end='')
stack_aux = []
for w in adjLists[v]:
if(not visited[w]):
stack_aux.append(w)
while(len(stack_aux)>0):
stack.append(stack_aux.pop())
# ------------------------------------------------------------------
# 0 1 2 3 4 5 6 7 8
adjLists1 = [ [1,2,3], [4], [5,6], [7,8], [], [9,10,11], [12,13,14], [], [] ]
dfs_iterative(adjLists1, 2)
答案 0 :(得分:0)
您可以通过使用列表中的最大值并防止进行适当的索引来解决没有空白子节点的问题:
您的代码也可以简化一下:
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]。