java - Finding all hamiltonian cycles -
i'm trying implement method adding possible hamiltonian cycles list using recursion. far stopping condition isn't sufficient , "outofmemoryerror: java heap space" in line adds vertex list:
private boolean gethamiltoniancycles(int first, int v, int[] parent, boolean[] isvisited, list<list<integer>> cycles) { isvisited[v] = true; if (allvisited(isvisited) && neighbors.get(v).contains(new integer(first))) { arraylist<integer> cycle = new arraylist<>(); 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; (int = 0; < neighbors.get(v).size(); i++) { int u = neighbors.get(v).get(i); parent[u] = v; if (!isvisited[u] && gethamiltoniancycles(first, u, parent, isvisited, cycles)) { cycleexists = true; } } //if (!cycleexists) { isvisited[v] = false; // backtrack //} return cycleexists; }
can please suggest me i'm doing wrong or approach incorrect?
edit: suggested in comments, culprit parent array, causing infinite loop. wasn't able correct , changed array store child element. seems work:
private boolean gethamiltoniancycles(int first, int v, int[] next, boolean[] isvisited, list<list<integer>> cycles) { isvisited[v] = true; if (allvisited(isvisited) && neighbors.get(v).contains(first)) { arraylist<integer> cycle = new arraylist<>(); int vertex = first; while (vertex != -1) { cycle.add(vertex); vertex = next[vertex]; } cycles.add(cycle); isvisited[v] = false; return true; } boolean cycleexists = false; (int u : neighbors.get(v)) { next[v] = u; if (!isvisited[u] && gethamiltoniancycles(first, u, next, isvisited, cycles)) { cycleexists = true; } } next[v] = -1; isvisited[v] = false; // backtrack return cycleexists; }
if looking disjoint hamiltonian cycles here have implementation using backtracking.
Comments
Post a Comment