Java中的骑士之旅之谜

时间:2019-03-27 18:00:43

标签: java debugging logic puzzle

我尝试编写骑士的巡回演算法进行练习,并使用了递归函数。似乎没有任何错误,但仅显示“解决方案不存在”。我需要一些调试指南,如果您知道一个可以帮助我的网站,请介绍

public class KnightSTour {
    static int n = 8;
    public static void main(String[] args) {

        int[][] chessboard = new int[n][n];
        initialization(chessboard);
        int[] horizontal = {2, 1, -1, -2, -2, -1, 1, 2 };
        int[] vertical = {1, 2, 2, 1, -1, -2, -2, -1};   
        chessboard[0][0] = 0;
        if (kt(0, 0, 1, chessboard, horizontal, vertical))
            show(chessboard);
        else
            System.out.print("solution does not exist\n");
    }
    public static boolean is_Safe(int row, int column, int[][] array) {
        return row >= 0 && row < n && column >= 0 && column < n && array[row][column] == -1;
    }
    public static boolean kt(int currentrow, int currentcolumn, int counter, int[][] chessboard, int[] horizontal, int[] vertical) {
        if (counter == n * n)
            return true;

        for (int k = 0; k < vertical.length; k++) {
            currentrow += horizontal[k];
            currentcolumn += vertical[k];
            if (is_Safe(currentrow, currentcolumn, chessboard)) {
                chessboard[currentrow][currentcolumn] = counter;
                if (kt(currentrow, currentcolumn, counter + 1, chessboard, horizontal, vertical))
                    return true;
                else
                    chessboard[currentrow][currentcolumn] = -1;
            }
        }
        return false;
    }
    public static void show(int[][] array) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                System.out.print(array[i][j] + "  ");
            }
            System.out.println();
        }
    }
    public static void initialization(int[][] array) {
        for (int i = 0; i < array.length; i++)
            for (int j = 0; j < array.length; j++)
                array[i][j] = -1;
    }
}

0 个答案:

没有答案