java - 找出所有的哈密顿循环

标签 java recursion hamiltonian-cycle

我正在尝试实现一种使用递归将所有可能的哈密顿循环添加到列表中的方法。到目前为止,我的停止条件是不够的,我在将顶点添加到列表的行中得到“OutOfMemoryError:Java heap space”:

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

有人可以告诉我我做错了什么或者我的方法完全不正确吗?

编辑: 正如评论中所建议的,罪魁祸首是父数组,导致无限循环。我无法更正它,我更改了数组来存储子元素。现在一切似乎都正常了:

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

最佳答案

如果您正在寻找不相交的哈密顿循环 here有一个使用回溯的实现。

关于java - 找出所有的哈密顿循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115942/

相关文章:

java - scala maven 插件没有将 scala 文件打包到 jar 中

java - android :text ="@string/hello" and normal right click--> Text view component--> EditText之间的区别

java - 如何在 Class<?> 的对象上执行方法

无法理解此代码的输出

algorithm - 什么是合适的算法?

c++ - 优化在网格图中查找哈密顿循环的函数?

Java 如何使用xpath提取完整的XML block

c# - 有没有办法在 C# 中阻止或断言意外递归

python - 如何使用递归编写 all_subsets 函数?

algorithm - 使用哈密尔顿循环函数和相反任务的哈密顿寻路