简体   繁体   English

钉接龙回溯无限循环

[英]Peg Solitaire backtracking infinite loop

I'm making a peg solitaire resolver with backtracking in java. 我正在用Java回溯制作挂钉单人纸牌解析器。

This is the method I've done: 这是我做过的方法:

private void solve(Board board, ArrayList<Movement> solution, Boolean result) {
    ArrayList<Movement> movs = board.getMovements();
    for (Movement movement : movs) {
        if (board.isMovementValid(movement)) {
            board.doMovement(movement);
            if(!board.isSolution()) {
                solution.add(movement);
                solve(board, solution, result);
                result.setValue(false);
            } else {
                result.setValue(true);
            }

        }
    }
    result.setValue(false);
}

The problem is that I can't find the solution. 问题是我找不到解决方案。 Here is the output of the code: http://pastebin.com/raw.php?i=BhkLu3qr . 这是代码的输出: http : //pastebin.com/raw.php?i=BhkLu3qr As you can see the solution array is incomplete. 如您所见,解决方案数组不完整。

Thanks. 谢谢。

Not so elegant, but in order to track back and retry an alternative the step must be taken back: 不太好用,但是为了回溯并重试另一种方法,必须退后一步:

ArrayList<Movement> movs = board.getMovements();
for (Movement movement : movs) {
    if (board.isMovementValid(movement)) {
        board.doMovement(movement);
        solution.add(movement);
        if(!board.isSolution()) {
            solve(board, solution, result);
            // Initialized to result.setValue(false);
            if (result.getValue()) { return; }
        } else {
            result.setValue(true);
            return;
        }
        solution.remove(movement);
        board.undoMovement(movement);
    }
}
result.setValue(false);

Also for a more general solution where you are satisfied with the first solution, I have added returns. 同样,对于您对第一个解决方案感到满意的更通用的解决方案,我还添加了退货。

Assuming that your board.getMovements() method gives you a list of all possible moves from this point in the game, you're almost there. 假设您的board.getMovements()方法为您提供了游戏中从这一点开始的所有可能动作的列表,那么您就board.getMovements()了。 You just need to stop when you win. 获胜时,您只需要停下来。 I've refactored at bit for clarity. 为了清楚起见,我进行了一点重构。

private boolean solve(Board board, ArrayList<Movement> solution) {
    // The base case: if it's already solved, we're done
    if (board.isSolution())
        return true;

    // Get all possible moves from this point
    ArrayList<Movement> movs = board.getMovements();
    for (Movement movement : movs) {
        if (board.isMovementValid(movement)) {
            board.doMovement(movement);
            solution.add(movement);
            if (solve(board, solution))
                // That move led to success :-)
                return true;
            else
                // That move led to failure :-(
                solution.remove(movement);
        }
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM