Search code examples
pythondepth-first-search

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? The else clause never executes even though there is a cycle. Did I miss anything? Thank you!


Solution

  • I think the issue is that you need to return the recursive call to check (after the if statement) making your code look like:

    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. Hope this helps you out!