Finding all hamiltonian cycles

可紊 提交于 2019-12-07 17:28:03

问题


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:

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;
    for (int i = 0; i < 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 someone please suggest me what I'm doing wrong or is my approach completely incorrect?

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:

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;
    for (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;
}

回答1:


If you is looking for Disjoint Hamiltonian Cycles here have an implementation using Backtracking.



来源:https://stackoverflow.com/questions/16115942/finding-all-hamiltonian-cycles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!