title: How to find if a graph has a cycle?
body: <p>I know this question has been asked many times in this forum and everywhere else in the internet. But before you attack me with your claws outstretched please bear with me.</p>
  
  <p>I am a newbie learning graph. As part of my excercise I am given to add a method hasCycle() in the Graph class here 
  <a href="http://homepage.cs.uiowa.edu/~sriram/21/fall05/ExamplePrograms/ReaderFiles/Chap13/dfs/dfs.java" rel="nofollow noreferrer">http://homepage.cs.uiowa.edu/~sriram/21/fall05/ExamplePrograms/ReaderFiles/Chap13/dfs/dfs.java</a>.</p>
  
  <p>My approach, doing a DFS as suggested in this forum here <a href="https://stackoverflow.com/questions/10972028/finding-a-cycle-in-an-undirected-graph-vs-finding-one-in-a-directed-graph?rq=1">Finding a cycle in an undirected graph vs finding one in a directed graph</a>.</p>
  
  <p>But I am struggling how to implement this using the existing dfs method in the first link.</p>
  
  <p>My approach so far has been:</p>
  
  <pre><code>public boolean hasCycle(int start)
  {
      vertexList[start].wasVisited = true;
      for(int j = 0; j &lt; MAX_VERTS; j++)
      {  
          if(adjMat[start][j]==1 &amp;&amp; vertexList[j].wasVisited==true)
          return true;
          else if(adjMat[start][j]==1 &amp;&amp; vertexList[j].wasVisited==false)
          {
           vertexList[start].wasVisited == true;
           hasCycle(j);
          }
      }
     return false;
  }
  </code></pre>
  
  <p>I have two problems here:
  First I am stuck into an infinite recursion when I call hasCycle() in the DFSApp class instead of the line
       theGraph.dfs(); 
  Second I am not using the given dfs() as reuired by my homework.</p>
  
  <p>Any direction to the right path would be appreciated in terms of what I am doing wrong here.</p>
  
  <p>For now I am just concentrating on implementing a correct separate hasCycle() method without using dfs().</p>