graph-algorithmpseudocodebreadth-first-searchcycle-detection

BFS cycle detection


Could someone provide a step by step pseudocode using BFS to search a cycle in a directed/undirected graph?

Can it get O(|V|+|E|) complexity?

I have seen only DFS implementation so far.


Solution

  • You can take a non-recursive DFS algorithm for detecting cycles in undirected graphs where you replace the stack for the nodes by a queue to get a BFS algorithm. It's straightforward:

    q <- new queue // for DFS you use just a stack
    append the start node of n in q
    while q is not empty do
        n <- remove first element of q
        if n is visited
            output 'Hurray, I found a cycle'
        mark n as visited
        for each edge (n, m) in E do
            append m to q
    

    Since BFS visits each node and each edge only once, you have a complexity of O(|V|+|E|).