【问题标题】:Depth-first search, Recursion, For loops, and Return深度优先搜索、递归、For 循环和返回
【发布时间】:2023-03-19 18:10:02
【问题描述】:

我正在尝试实现 DFS 算法来确定 start 节点和 target 节点之间是否存在路径。这是我到目前为止的代码:

# Depth-first search
def find_path2(s, t):
    s.visited = True

    if s.data == t.data:
        return True

    for node in s.neighbors:
        if not node.visited:
            return find_path2(graph, node, t)


node_0 = Node(0)
node_1 = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
node_6 = Node(6)

node_0.neighbors = [node_1]
node_1.neighbors = [node_2]
node_2.neighbors = [node_3, node_0]
node_3.neighbors = [node_2]
node_4.neighbros = [node_6]
node_5.neighbros = [node_4]
node_6.neighbors = [node_5]

start = node_2
target = node_0


if find_path2(start, target):
    print("There is a path between {} and {}".format(start.data, target.data))
else:
    print("There is no path between {} and {}".format(start.data, target.data))

node_2 有 node_3 和 node_0 作为邻居,所以它应该打印它们之间有一条路径。我知道 return 语句在第一次执行期间退出了 for 循环,因为 return 语句退出了函数,因此从不访问 node_0。

我的问题是,最优雅的方法是什么?谢谢!

【问题讨论】:

  • 这段代码是否按预期工作?维基百科上的 DFS 伪代码很简单,IMO。我认为find_path2(my_graph, node, t) 处的代码错误,因为my_graph 不存在并且只有2 个参数要传递
  • 代码中有很多错误,但您描述的问题可能会发生,因为您只考虑find_path2 中的一个邻居。您可以尝试将for 循环替换为return any(find_path2(node, t) for node in s.neighbors if not node.visited)。
  • my_graph 是一个旧参数,我忘记了,但在测试时我已将其删除。

标签: python for-loop recursion return depth-first-search


【解决方案1】:

如果你找到了你正在寻找的节点,你需要确保你只从邻居的循环中返回:

def find_path2(s, t):
    s.visited = True

    if s.data == t.data:
        return True

    for node in s.neighbors:
        if not node.visited:
            if find_path2(node, t):
                return True
    return False

【讨论】:

  • 谢谢!这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
相关资源
最近更新 更多