title: Finding all cycles in a directed graph using recursive backtracking
body: <p>I am working on finding cycles in directed graph using recursive backtracking. There is a suggested pseudocode for this <a href="https://stackoverflow.com/questions/546655/finding-all-cycles-in-graph">here</a>, which is here:</p>
  
  <pre><code>dfs(adj,node,visited):  
    if (visited[node]):  
      if (node == start):  
        "found a path"  
      return;  
    visited[node]=YES;  
    for child in adj[node]:  
      dfs(adj,child,visited)
    visited[node]=NO;
  </code></pre>
  
  <p>Call the above function with the start node:</p>
  
  <pre><code>visited = {}
  dfs(adj,start,visited)
  </code></pre>
  
  <p>While this is not the most efficient algorithm when compared to <code>Tarjans algorithm</code>, this is simple enough me for me to understand. Currently, this code does not have a count of number cycles detected.</p>
  
  <p>I implemented this in Java:</p>
  
  <pre><code>//this is the main method that calls the helper DFS which runs on each node
  public int allCyclesDirectedmain(){
      //this initializes all vertices
      clearAll();
      int[] count = new int[1];
      for (Vertex v: vertexMap.values()){
          //System.out.println(v.name);
          //clearAll();
          dfs(v,v,count);
      }
      return count[0];
  }
  
  //start and v are same when the method first fires.
  public void dfs(Vertex start, Vertex v,int[] count){
     if (v.isVisited){
         if (start==v){
             //found a path
             count[0]++;
         }
         return ;
     }
     v.setVisited(true);
     for (Edge e : v.adj){
         Vertex next = e.target;
         dfs(start,next,count);
     }
     v.setVisited(false);
  }
  </code></pre>
  
  <p>For the graph with following edges:<br>
  <code>(1 2),(2 3),(3 1),(2 5),(5 6),(6 2)</code>-- I get 6 cycles as output.</p>
  
  <p><code>(1 2),(2 3),(3 4),(4,1),(2 5),(5 6),(6 2)</code> -- I get 7 cycles as output.</p>
  
  <p>I can see that my current code does cycle detection for each vertex that are already part of a previously detected cycle (e.g.: a cycle with three nodes gives me three cycles for each individual nodes while this must be one). I need some tips here as to what is going wrong and some fix.</p>