简体   繁体   English

如何使用 DFS 正确检测循环?

[英]How to correctly detect cycle using DFS?

Here are my codes for detecting a cycle in a graph:这是我在图中检测循环的代码:

seen = set()

def check(table,node):

    seen.add(node)

    #traverse all neighors of the current node

    for neigh in table[node]:
        print(neigh, seen)

        if neigh not in seen:
            check(table,neigh)
        else:
            return False
    return True



table1 = {'A':['B'],'B':['A']}

print(check(table1,'A'))

Why it always returns True?为什么它总是返回 True? The else clause never executes even though there is a cycle.即使存在循环,else 子句也不会执行。 Did I miss anything?我错过了什么吗? Thank you!谢谢!

I think the issue is that you need to return the recursive call to check (after the if statement) making your code look like:我认为问题在于您需要返回递归调用以check (在 if 语句之后)使您的代码看起来像:

seen = set()

def check(table,node):

    seen.add(node)

    #traverse all neighors of the current node

    for neigh in table[node]:
        print(neigh, seen)

        if neigh not in seen:
            return check(table,neigh)
        else:
            return False
    return True



table1 = {'A':['B'],'B':['A']}

print(check(table1,'A'))

what happens with your original code is you recursively call check with node "B", it returns false, but you don't do anything with that returned value so on the top level it exits the for loop and returns true to the user.您的原始代码会发生什么情况是您使用节点“B”递归调用 check,它返回 false,但您不对该返回值执行任何操作,因此在顶层它退出 for 循环并向用户返回 true。 Hope this helps you out!希望这可以帮助你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM