【问题标题】:Finding all hamiltonian cycles找到所有的哈密顿循环
【发布时间】:2013-04-13 12:21:52
【问题描述】:

我正在尝试实现一种使用递归将所有可能的哈密顿循环添加到列表的方法。到目前为止,我的停止条件还不够,我在将顶点添加到列表的行中得到“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;
}

有人可以建议我做错了什么还是我的方法完全不正确?

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

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

【问题讨论】:

  • 您确定parent 中始终存在等于-1 的可达元素吗?
  • 此方法的 external 调用的参数是什么?您是否尝试过在调试器下运行整个代码?

标签: java recursion hamiltonian-cycle


【解决方案1】:

如果您正在寻找不相交哈密顿循环here,请使用回溯实现。

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多