【问题标题】:DFS search not returning certain nodes in my listDFS 搜索未返回我列表中的某些节点
【发布时间】:2016-02-23 04:39:33
【问题描述】:

我将这个实现用于 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_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)

【问题讨论】:

  • 您的邻接列表包含 9 个元素(内部 -lists)。因此 n 等于 9 并且您创建了一个长度为 9 的访问数组。但是当您尝试从节点 2 启动 DFS 时,您会转到 5,6。然后你尝试探索 6,这将引导你到节点 12、13、14。您访问的列表中没有第 14 个元素。
  • 我现在明白了。我在列表中添加了空元素以将长度扩展到 14,现在我可以看到子节点。不是一个很好的修复,但它现在有效。谢谢

标签: python search depth-first-search


【解决方案1】:

您可以在没有空白子节点的情况下解决问题,方法是使用列表中的最大值并适当防止索引:

你的代码也可以简化一点:

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]。

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多