javagraphdirected-acyclic-graphsmicrosoft-distributed-file-system

Cycle detection in directed Graph using DFS based on stack


Below algo is failing after stack overflow exception. Please let me know how can i correct it for cycle detection in Directed Graph or if possible can somebody provide algo based on stack instead of recursion.

public boolean hasCycle(Graphnode<T> n) {

    n.setMark(IN_PROGRESS);

    for (Graphnode<T> m : n.getSuccessors()) {
        if (m.getMark() == IN_PROGRESS) {
            return true;
        }

        if (m.getMark() != DONE) {
            if (hasCycle(m)) {
                return true;
              }
        }
    }

    n.setMark(DONE);

    return false;
}

Thanks, Vikrant


Solution

  • I haven't done this kind of stuff for a long time but your code seems weird. Your first if-condition is :

    if (m.getMark() == IN_PROGRESS) {
    
    return true;
    }
    

    I think it should be this instead :

    if (m.getMark() == IN_DONE) {
    
    return true;
    }
    

    If not, what is the difference between m.getMark() == IN_PROGRESS and m.getMark() != DONE ? Your second if-condition is never triggered.

    Note: If you go through SO you will find many algorithms using DFS or stacks...