Search code examples
javacycleinfinite-loopdepth-first-search

Stack overflow from infinite loop - detecting cycles in modified DFS


I am going a bit crazy at this point trying to determine the source of an infinite loop (getting a stackoverflow error). I am trying to implement a modified DFS to detect cycles in a graph. I am working off of this example on page 11: http://www.cs.berkeley.edu/~kamil/teaching/sp03/041403.pdf

In this implementation, 0 = WHITE, 1 = GRAY, and 2 = BLACK. I am hoping that I am missing something relatively simple.

public boolean containsCycle()
 {
   for (int i=0; i<n; i++)
     marks[i] = 0; // Initialize all to zero - unvisited

   for (int i=0; i<n; i++) { // n = number of vertices in the graph
     if (marks[i]==0) {
       if (visit(i)){
         return true;
       }
     }
   }
   return false;
 }

public boolean visit(int index){
    marks[index] = 1; // Visited

    for (int i=0; i<n; i++){
       if(isArc(index,i)){ // isArc() returns true IFF there is a directed edge from index->
        if (marks[i]==1)
         return true;
      }
      else if (marks[i]==0) {
        if(visit(marks[i])) 
        return true;
      }
    }
    marks[index] = 2;
    return false;
  }

Solution

  • Seems it should be else if (visit(i)) instead of else if (visit(marks[i]))