我試圖用回溯來解決騎士的旅程問題。我認爲我應該使用的算法。我試過了,但我無法弄清楚它爲什麼不起作用。它導致無限循環。騎士之旅 - 導致無限循環,我無法弄清楚爲什麼
但是,如果我註釋掉回線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;
}
你是什麼意思,它在你刪除該行時起作用?它是否終止,還是找到正確的解決方案?你確定它不是很慢嗎? –
它終止並找到正確的解決方案。 – 12rad
當我在沒有該行的情況下運行它時,它只返回'false',並且如果我打印「解決方案」,則其中有重複的數字。 –