日期:2014-05-20  浏览次数:20819 次

KnightTour 骑士遍历问题
程序似乎有点问题 但是我还找不到原因 求解啊
结果中37和62好象是一样的 还有很多一样的 不知道怎么办
Java code
public class tour {
    final static public int M = 8;//
    static public int[][] path = new int[M][M];// 记录步子的数组
    final static int[] dx = new int[] { 2, 1, -1, -2, -2, -1, 1, 2 };
    final static int[] dy = new int[] { -1, -2, -2, -1, 1, 2, 2, 1 };// pose
    public static int counter = 0;
    public static int total = 0;

    public tour() {

    }

    public static void initpath() {
        for (int i = 0; i < M; i++)
            for (int j = 0; j < M; j++)
                path[i][j] = 0;// 将数组初始为0
    }

    static public void display() {

        for (int i = 0; i < M; i++)
            for (int j = 0; j < M; j++) {
                initpath();
                counter = 0;
                set(i, j);

                // initpath();
            }
    }

    public static void set(int x, int y) {

        if (test(x, y)) {
            path[x][y] = counter++;

            /* System.out.println(counter); */
            if (counter == M * M + 1) {
                total++;
                System.out.printf("第%d种\n", total);
                for (int s = 0; s < M; s++) {
                    for (int t = 0; t < M; t++)
                        System.out.printf("%2d ", path[s][t]);
                    System.out.println();
                }

            }// 打印
            //System.out.println();
            for (int i = 0; i < 8; i++) {
                set(x + dx[i], y + dy[i]);
            }
        }

    }

    private static boolean test(int x, int y) {
        if (x < 0 || x >= M || y < 0 || y >= M)
            return false;
        else if (path[x][y] == 0)
            return true;
        return false;
    }

    public static void main(String args[]) {
        display();
    }

}



------解决方案--------------------
static public void display() {

for (int i = 0; i < M; i++)
for (int j = 0; j < M; j++) {
initpath();
counter = 0;
set(i, j);

// initpath();
}
}

将这里的counter=0改为=1,这回输出结果都不同了,第i种方案里第i个位置为第一步
------解决方案--------------------
骑士每次走会有4个方向可供选择,之前的方法count=0,传进去之后第一步并未标为1,而是从第二位开始算起,所以有重复的。
话说虽然现在第i种方法中第i个位置为第一步,但是同样的起点不能有两种以上走法吗?没研究过这问题。。