title: Finding all hamiltonian cycles
body: <p>I'm trying to implement a method for adding all possible Hamiltonian cycles to a list using recursion. So far my stopping condition isn't sufficient and I get "OutOfMemoryError: Java heap space" in the line that adds a vertex to a list:</p>
  
  <pre><code>private boolean getHamiltonianCycles(int first, int v, int[] parent,
          boolean[] isVisited, List&lt;List&lt;Integer&gt;&gt; cycles) {
      isVisited[v] = true;
      if (allVisited(isVisited) &amp;&amp; neighbors.get(v).contains(new Integer(first))) {
          ArrayList&lt;Integer&gt; cycle = new ArrayList&lt;&gt;();
          int vertex = v;
          while (vertex != -1) {
              cycle.add(vertex);
              vertex = parent[vertex];
          }
          cycles.add(cycle);
          return true;
      } else if (allVisited(isVisited)) {
          isVisited[v] = false;
          return false;
      }
      boolean cycleExists = false;
      for (int i = 0; i &lt; neighbors.get(v).size(); i++) {
          int u = neighbors.get(v).get(i);
          parent[u] = v;
          if (!isVisited[u]
                  &amp;&amp; getHamiltonianCycles(first, u, parent, isVisited, cycles)) {
              cycleExists = true;
          }
      }
      //if (!cycleExists) {
          isVisited[v] = false; // Backtrack
      //}
      return cycleExists;
  }
  </code></pre>
  
  <p>Can someone please suggest me what I'm doing wrong or is my approach completely incorrect?</p>
  
  <p>EDIT:
  As suggested in comments, the culprit was the parent array, causing an infinite loop. I wasn't able to correct it and I changed the array to store the child element. Now everything seems to work:</p>
  
  <pre><code>private boolean getHamiltonianCycles(int first, int v, int[] next,
          boolean[] isVisited, List&lt;List&lt;Integer&gt;&gt; cycles) {
      isVisited[v] = true;
      if (allVisited(isVisited) &amp;&amp; neighbors.get(v).contains(first)) {
          ArrayList&lt;Integer&gt; cycle = new ArrayList&lt;&gt;();
          int vertex = first;
          while (vertex != -1) {
              cycle.add(vertex);
              vertex = next[vertex];
          }
          cycles.add(cycle);
          isVisited[v] = false;
          return true;
      }
      boolean cycleExists = false;
      for (int u : neighbors.get(v)) {
          next[v] = u;
          if (!isVisited[u]
                  &amp;&amp; getHamiltonianCycles(first, u, next, isVisited, cycles)) {
              cycleExists = true;
          }
      }
  
      next[v] = -1;
      isVisited[v] = false; // Backtrack
      return cycleExists;
  }
  </code></pre>