高峰时间解算器遇到无限循环任何非平凡的谜题

时间:2016-09-14 21:48:43

标签: java

所以我正在用Java写一个尖峰时间解算器,这意味着能够解决配置here。但是,即使是该页面中最简单的拼图,也会导致求解器无限运行并最终耗尽内存。我正在使用广度优先搜索来完成从每个板状态产生的所有可能移动(使用HashSet以确保我不重复自己),并将每个状态映射到移动到那里以便我可以回溯通过他们以后。

问题是,我已经尝试了更多琐碎的谜题,我自己想出来了,它能够解决它们(尽管很慢)。

我是如何接近这个问题的?如果需要的话,我也可以从相关的类中提供一些代码,但我已经对它们进行了相当彻底的测试,我很确定问题出在下面的代码中。我的直觉说它与HashSet有关,并确保我不重复自己(因为队列的大小经常达到数十万)。

有什么建议吗?

    // Start at the original configuration
    queue.add(originalBoard);

    // We add this to our map, but getting here did not require a move, so we use
    // a dummy move as a placeholder move
    previous.put(originalBoard, new Move(-1, -1, "up"));

    // Breadth first search through all possible configurations
    while(!queue.isEmpty()) {
        // Dequeue next board and make sure it is unique
        Board currentBoard = queue.poll();
        if (currentBoard == null)           continue;
        if (seen.contains(currentBoard))    continue;
        seen.add(currentBoard);

        // Check if we've won
        if (currentBoard.hasWon()) {
            System.out.println("We won!");
            currentBoard.renderBoard();
            return solved(currentBoard);
        }

        // Get a list of all possible moves for the current board state
        ArrayList<Move> possibleMoves = currentBoard.allPossibleMoves();

        // Check if one of these moves is the winning move
        for (Move move : possibleMoves) {
            Board newBoard = move.execute(currentBoard);

            // We don't need to enqueue boards we've already seen
            if (seen.contains(newBoard))   continue;
            queue.add(newBoard);

            // Map this board to the move that got it there
            previous.put(newBoard, move);
        }
    }

根据要求,这是我对HashSet的初始化(它们是类级变量):

private static HashSet<Board> seen = new HashSet<>();

我的Board.equals()方法:

@Override
public boolean equals (Object b) {
    Board otherBoard = (Board) b;
    boolean equal = false;
    if (this.M == otherBoard.getM() && this.N == otherBoard.getN()) {
        equal = true;

        // Each board has an ArrayList of Car objects, and boards are only
        // considered equal if they contain the exact same cars
        for (Car car : this.cars) {
            if (otherBoard.getCar(car.getPosition()) == null) {
                equal = false;
            }
        }
    }
    System.out.println(equal);
    return equal;
}

1 个答案:

答案 0 :(得分:1)

您必须实现Board.hashCode()以覆盖默认的基于Object的版本,以这种方式,根据其合约,任何两个相等的Board对象具有相同的哈希码。如果你不这样做,那么你的seen集实际上根本无法完成任何事情。

在另一个问题上,我怀疑你检查电路板车的方式并不完全正确。如果按照我认为的方式工作,它会认为这两个板是相同的: . =空格 * =汽车的一部分

......
.**.*.
....*.
.*....
.*.**.
......

......
.*..**
.*....
......
.**.*.
....*.