我正在尝试使用回溯解决骑士的旅行问题。我认为我拥有的算法应该可以工作。我试过了,但我不知道为什么它不起作用。它导致无限循环。
但是,如果我注释掉回溯的行,solutionBoard[dst.x][dst.y]=-1;
它就可以工作!我只是不明白为什么!任何帮助,将不胜感激。
private int solutionBoard[][] = new int [8][8];
// The eight possible moves a knight can make from any given position
private static final Point[] MOVES = new Point[] { new Point(-2, -1),
new Point(-2, 1), new Point(2, -1), new Point(2, 1),
new Point(-1, -2), new Point(-1, 2), new Point(1, -2),
new Point(1, 2) };
private int count = 0;
public KnightsTour_DFS(){
// board is 0- 7
//initialize visited
for(int i =0; i<8;i++){
for(int j = 0; j< 8; j++){
solutionBoard[i][j] = -1;
}
}
solutionBoard[0][0]=count++;
if(findTour(0, 0)){
System.out.println("Tour found!!");
printSolution();
}
}
public boolean findTour(int x, int y){
if(x <0 || y <0 || x>7 || y > 7 ){
return false;
}
if(count == 64){
//we've covered all node
return true;
}
for(int i = 0; i < this.MOVES.length; i++){
Point dst = new Point(x + MOVES[i].x, y + MOVES[i].y);
if(canMove(dst)){
solutionBoard[dst.x][dst.y]=count++;
if(findTour(dst.x, dst.y)){
System.out.println("Solution shown on board\n");
return true;
}
else{
count --;
solutionBoard[dst.x][dst.y]=-1;
}
}
}
return false;
}
private void printSolution() {
System.out.println("Solution shown on board\n");
for (int[] rows : solutionBoard) {
for (int r : rows) {
System.out.printf("%2d ", r);
}
System.out.println();
}
}
public boolean canMove(Point destination){
if(destination.x<0 || destination.y<0 || destination.x>7|| destination.y>7){
return false;
}
if(solutionBoard[destination.x][destination.y] != -1){
//already visited
return false;
}
return true;
}