簡體   English   中英

使用 DFS 在圖中查找循環 - 遞歸問題

[英]Finding cycle in graph using DFS - recursion problem

我試圖制作一個在無向圖中搜索循環的算法,但似乎 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,但它還會兩次打印消息“找到循環”。 那么如果它執行打印 function 為什么它不返回 True? 我的停止條件有什么問題嗎?

好的,我發現了問題。 我在調用 Wrapped_dfs_recursive() 時錯過了“返回”這個詞,所以它沒有改變任何東西,最后返回了 False。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM