【发布时间】:2014-01-12 01:57:31
【问题描述】:
我正在尝试使用 java 中的回溯和递归解决 4x4 板上的骑士之旅问题,并且在输出中我得到以下步骤顺序:
1 13 16 15
10 7 4 14
5 2 11 8
12 9 6 3
在右上角,14、15和16相邻,这是不可能的,因为骑士在棋盘上移动成L形。如果有人可以帮助我解决这个问题,我将不胜感激。
代码:
public class KnightsTour {
private static int board[][] = new int[4][4];
private static int stepCounter = 1;
public Test() {
initBoard(board);
tour(0,0);
printSol(board);
}
public static void printSol(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if(a[i][j]>9){
System.out.print(a[i][j] + " ");
}else{
System.out.print(a[i][j] + " ");
}
}
System.out.println();
}
System.out.println();
}
public static void initBoard(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = -1;
}
}
}
public void tour(int x, int y) {
if (((x < 0) || (x >= 4) || (y < 0) || (y >= 4)) || (board[x][y] != -1)) {
return;
}else{
board[x][y] = stepCounter++;
tour(x+2, y+1);
tour(x+1, y-2);
tour(x+1, y+2);
tour(x-1, y+2);
tour(x-2, y-1);
tour(x-2, y+1);
tour(x-1, y-2);
tour(x+2, y-1);
}
}
public static void main(String[] args){
new KnightsTour();
}
}
【问题讨论】:
-
我对骑士之旅不熟悉,所以我用谷歌搜索了它,first result 提出了一个论坛帖子......其中第三个答案是“骑士不能游览 4x4 board”...我不确定这是否真的不可能...但我会在尝试对其进行编码之前找出答案 XD
-
我在 8x8 板上遇到了同样的问题
-
是的,看看this image,您只能访问路径图像左侧或右侧的所有四个字母一次,不能同时访问。
标签: java recursion backtracking knights-tour