我是编程新手,想要解决Knights Tour问题。所以我试了一下。我刚学会了递归的概念,并试图用它来解决4X4板的这个问题。我的代码是:
public class Knight_tour{
private static boolean[][] chessboard = new boolean[4][4];
public static void Knight_tour(int x,int y) {
if(((x < 0) || (x >= 4) || (y <0) || (y >= 4))){
//do nothing
}else{
if(chessboard[x][y] == true){
//if it is already visited, then, do nothing.
}
if(chessboard[x][y] != true) {
//If it is not visited then find more points like this.
chessboard[x][y]=true;
System.out.println(x +" "+ y);
Knight_tour(x+2, y+1);
Knight_tour(x+1, y-2);
Knight_tour(x+1, y+2);
Knight_tour(x-1, y+2);
Knight_tour(x-2, y-1);
Knight_tour(x-2, y+1);
Knight_tour(x-1, y-2);
Knight_tour(x+2, y-1);
}
}
}
public static void main(String[] args){
Knight_tour(0, 1);
}
}
现在当我运行它时,我得到以下输出:
0 1
2 2
3 0
1 1
3 2
1 3
2 1
3 3
1 2
2 0
0 0
3 1
2 3
0 2
1 0
0 3
这给了我按照访问顺序在棋盘上的方框位置。我的问题是:
点0,0变为3,1,倒数第二点为1.0,从那里变为0,3。它不应该这样做,我试图解决这个问题,但我不能。任何人都可以帮我解决这个问题并告诉我这是怎么回事以及为什么会这样。
这样可以解决吗?我的意思是我确定有许多复杂和更复杂的算法,但我只想要一些东西来练习递归。我学会了DFS算法,有点觉得,这需要同样的东西。如果它不能,可以任何人都指出了我正确的方向(一种简单的方法来实现这一点,它不需要针对速度或任何事情进行优化)。
感谢。
答案 0 :(得分:2)
这里有一些问题:
你需要去思考你的算法,或者阅读其他人的解决方案。
答案 1 :(得分:1)
仅仅因为你打印出0,0然后3,1并不意味着3,1直接从 0,0访问。你所知道的是,在 0,0之后的某个时间,访问了3,1。
以下是您的程序的修改版本,通过打印出每个广场的访问位置来演示:
public class Knight_tour{
private static boolean[][] chessboard = new boolean[4][4];
public static void Knight_tour(int x,int y, int fromX, int fromY) {
if(((x < 0) || (x >= 4) || (y <0) || (y >= 4))){
//do nothing
}else{
if(chessboard[x][y] == true){
//if it is already visited, then, do nothing.
}
if(chessboard[x][y] != true) {
//If it is not visited then find more points like this.
chessboard[x][y]=true;
System.out.println(x +" "+ y + " (visited from " + fromX + ", " + fromY + ")");
Knight_tour(x+2, y+1, x, y);
Knight_tour(x+1, y-2, x, y);
Knight_tour(x+1, y+2, x, y);
Knight_tour(x-1, y+2, x, y);
Knight_tour(x-2, y-1, x, y);
Knight_tour(x-2, y+1, x, y);
Knight_tour(x-1, y-2, x, y);
Knight_tour(x+2, y-1, x, y);
}
}
}
public static void main(String[] args){
Knight_tour(0, 1, 0, 1);
}
}
输出:
0 1 (visited from 0, 1)
2 2 (visited from 0, 1)
3 0 (visited from 2, 2)
1 1 (visited from 3, 0)
3 2 (visited from 1, 1)
1 3 (visited from 3, 2)
2 1 (visited from 1, 3)
3 3 (visited from 2, 1)
1 2 (visited from 3, 3)
2 0 (visited from 1, 2)
0 0 (visited from 1, 2)
3 1 (visited from 1, 2)
2 3 (visited from 3, 1)
0 2 (visited from 2, 3)
1 0 (visited from 0, 2)
0 3 (visited from 1, 1)