【问题标题】:Finding cycle in graph using DFS - recursion problem使用 DFS 在图中查找循环 - 递归问题
【发布时间】:2021-03-13 08:27:45
【问题描述】:

我试图制作一个在无向图中搜索循环的算法,但似乎 return 语句不起作用。

def wrapped_dfs_recursive(G: Dict[int, List[int]], current_vertex: int, parent: int, visited: List[int] = None):
    
    for neighbour in G[current_vertex]:
        if neighbour in visited and neighbour != parent:
            print("Found cycle")
            return True

    visited.append(current_vertex)

    if current_vertex in G.keys():
        for vertex in G[current_vertex]:
            if vertex not in visited:
                wrapped_dfs_recursive(G, current_vertex=vertex, parent=current_vertex, visited=visited)
    else:
        return None
    return False

当我为一个简单的循环图执行此代码时,它返回 False,但它还会两次打印消息“找到循环”。那么如果它执行打印函数为什么不返回True呢?我的停止条件有什么问题吗?

【问题讨论】:

  • 你能举个例子吗?
  • 例如cyclic = {1: [2, 4], 2: [1, 3], 3: [2, 4], 4: [3, 1]}

标签: python


【解决方案1】:

好的,我找到了问题。我在调用 Wrapped_dfs_recursive() 时错过了“返回”这个词,所以它没有改变任何东西,最后返回了 False。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2023-04-05
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    相关资源
    最近更新 更多