Stack Overflow Error Knights Tour

时间:2017-11-22 01:16:29

标签: java stack-overflow

我有这个Knight的游览代码,但我在第37行得到了一个java.lang.StackOverflowError。我不确定从这里去修复它。我认为我的主要代码与它有关,但我不知道此时该怎么做。非常感谢任何帮助。

public class Main {
public static void main(String[] args) {
    Main tour = new Main();
    tour.solveKnightTour();
}
private static int chessboard[][];
boolean a = true;
public Main() {
    chessboard = new int[8][8];
}
private void matrixChessBoard() {
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            System.out.printf("%5d", chessboard[i][j]);
        }
        System.out.println();
    }
}
static boolean tour(int advance, int horizontal, int vertical, int xMove[], int yMove[]) {
    int i = 0;
    int moveHoriz = 0;
    int moveVert = 0;
    boolean a = true;
    chessboard[horizontal][vertical] = advance;
    if (advance == 63) {
        for (int t = 0; t < 8; t++) {
            for (int u = 0; u < 8; u++) {
                System.out.printf("%5d", chessboard[t][u]);
            }
            System.out.println("\n");
        }
    } else {
        for (int j = 0; j < 8; j++) {
            if ((horizontal + xMove[j] < 8 & (vertical + yMove[j]) >= 0 & (vertical + yMove[i]) < 8)
                    & (horizontal + xMove[i]) >= 0){
                if (chessboard[horizontal + xMove[i]][vertical + yMove[i]] == -1){
//line 37           if (tour(moveHoriz, moveVert, advance + 1, xMove, yMove)){
                        break;
                    }
                }
            }
        }
        a = false;
        chessboard[horizontal][vertical] = -1;
    }
    return a;
}
public boolean solveKnightTour() {
    for (int x = 0; x < 8; x++) {
        for (int y = 0; y < 8; y++) {
            chessboard[x][y] = -1;
        }
    }
    int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
    int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
    chessboard[0][0] = 0;
    if (!tour(0, 0, 1, xMove, yMove)) {
        return false;
    } else {
        matrixChessBoard();
    }
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

考虑tour()方法的精简版:

static boolean tour(int advance, int horizontal, int vertical, ...) {
    int moveHoriz = 0;
    int moveVert = 0;
    if (false) {
        ...
    } else {
        if (true)
            tour(moveHoriz, moveVert, advance + 1, ...);
    }
}

使用tour(0, 0, 1, ...)调用,该函数将以advance=0输入。将完成各种分配,将进行各种测试,然后执行tour(moveHoriz, moveVert, advance+1, ...)语句,该语句将评估为tour(0, 0, 1, ...)。重复直到堆栈溢出。

  • moveHoriz传递给advance参数
  • moveVert传递给horizontal参数
  • advance+1传递给vertical参数

这显然不是你想要的。由于advance+1未传递给advance,因此if (advance == 63)条件将始终评估为false,并且您永远不会退出递归。