奈特的巡回赛递归并没有找到解决方案

时间:2016-10-25 09:14:36

标签: java algorithm recursion graph-algorithm backtracking

之前曾问过奈特的巡演,但我仍然遇到麻烦。我正在尝试一次递归来访问棋盘的所有细胞,但我不能进行超过52次的访问。之后它回溯并且访问过的单元数量减少。这是我的代码:

public class Ch7E22_3 {
    public static int[][] chess;
    public static int[][] adjacent;

    public static void main(String[] args) {
        chess = new int[8][8];
        adjacent = new int[][] { { 2, 1 }, { 2, -1 }, { -2, 1 }, { -2, -1 }, { 1, 2 }, { -1, 2 }, { 1, -2 },
                { -1, -2 } };
        initializeChess();
        move(1, 0, 0);
    }

    private static void move(int cnt, int row, int col) {
        chess[row][col] = cnt;
        if (cnt == (8 * 8)) {
            System.out.println("You moved around all cells: " + cnt);
        } else {
            for (int i = 0; i < 8; i++) {
                if (((row + adjacent[i][0] >= 0) && (row + adjacent[i][0]) < 8)
                        && ((col + adjacent[i][1] >= 0) && (col + adjacent[i][1] < 8))) {
                    if (chess[row + adjacent[i][0]][col + adjacent[i][1]] == 0) {
                        row = row + adjacent[i][0];
                        col = col + adjacent[i][1];
                        cnt++;
                        System.out.println(row + "  " + col + "  cnt = " + cnt);
                        move(cnt, row, col);
                    }
                }
            }
        }
        chess[row][col] = 0;
    }

    private static void initializeChess() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                chess[i][j] = 0;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

第一个问题在这里:

for (int i = 0; i < 8; i++) {

所以,你有这个循环。让我们假设您在51输入cnt。

现在你有了

if ( ... some overly complicated condition ... ) {
  ... cnt++
  move(cnt,

现在发生的事情是:首先进行递归通话,如果点击,可能每次时间正确。因此,你增加cnt并再次递归。因此,您的打印输出显示cnt如何不断增加。

但在某些时候,递归结束 - if条件不再为真。所以递归调用的方法......结束了。但请记住:您通过另一次调用移动来调用该方法。那个人可能仍然在循环。更重要的是, move()有自己的版本的cnt。

要了解我的意思:将cnt从方法本地变量更改为您的类的字段,类似于您的电路板!当你这样做时,你会发现你的代码实际打印出来了:

...
3  7  cnt = 52
2  4  cnt = 53
...
2  3  cnt = 64
You moved around all cells: 64
0  4  cnt = 65
...

以后用

实际停止
4  0  cnt = 126

含义:打印cnt只是算法不能正常工作的副作用!

最后:我建议将if条件分解为一组小辅助方法,例如

private static isXyz(...)

并在if语句中调用这些方法 - 这将极大地提高可读性!

答案 1 :(得分:1)

您的回溯不正确。到最后一行执行时,将chess[row][col]设置为零,rowcol几乎肯定会发生变化。

最好不要在方法中更改rowcolcnt,而只是将新值传递给递归调用。这样的事情,虽然我没有检查你的其余逻辑:

    for (int i = 0; i < 8; i++) {
        int nextrow = row + adjacent[i][0];
        int nextcol = col + adjacent[i][1];
        if (nextrow >= 0 && nextrow < 8 &&
                nextcol >= 0 && nextcol < 8) {
            if (chess[nextrow][nextcol] == 0) {
                System.out.println(nextrow + "  " + nextcol + "  cnt = " + (cnt+1));
                move(cnt+1, nextrow, nextcol);
            }
        }
    }

为确保您只修改传递给后续递归调用的值,并且从不在方法中修改它们,您可以使参数最终:

private static void move(final int cnt, final int row, final int col) {
    ...
}