[英]Knight's tour in java (recursive)
我正在編寫經典騎士之旅的代碼,我的代碼似乎大部分都在做正確的事,但對於可能的開發板來說,這仍然給我“不可能”,我不知道為什么。 (例如:對於從第1行,第3列開始的,具有3行,4列的表,它將失敗)。 當計算行和列時,我從索引0開始。 我認為回溯不正確。 誰能幫我指出我的錯誤? 謝謝
import java.util.*;
public class KnightGame
{
private int rows;
private int cols;
private int [][] array;
public void initializeArray()
{
array = new int [rows][cols];
}
public boolean fill (int x, int y, int n)
{
if ( x < 0 || x >= rows || y<0 || y >= cols ) //outside of board
return false;
else if (array[x][y] != 0) //location has been visited, array element occupied
return false;
else if ( n == (rows * cols)) //have visited all locations
return true;
else
{
array[x][y] = n;
if ( fill(x+1, y-2, n+1) || fill(x-2, y+1, n+1) || fill(x+1, y+2, n+1)
|| fill(x+2, y+1, n+1) || fill(x-2, y-1, n+1) || fill(x-1, y-2, n+1) ||
fill(x-1, y+2, n+1) || fill(x+2, y-1, n+1))
return true;
else
return false;
}
}
public static void main (String [] args)
{
KnightGame game = new KnightGame();
int [] st = new int [2];
int startx, starty;
Scanner keyIn = new Scanner (System.in);
System.out.println("Enter number of rows: ");
game.rows=keyIn.nextInt();
System.out.println("Enter number of columns: ");
game.cols = keyIn.nextInt();
game.initializeArray();
System.out.println("Enter starting location: ");
for (int i=0; i<2; i++)
{
st[i] = keyIn.nextInt();
}
startx = st[0];
starty = st[1];
//testing for correct starting values
System.out.println("starting values: " + startx + " " + starty);
if (game.fill(startx, starty, 1))
{
for (int i=0; i<game.rows; i++)
{
for (int j=0; j<game.cols; j++)
{
System.out.print(game.array[i][j] + " ");
}
}
}
else
System.out.println("Board could not be completed!");
}
}
回溯時,您並沒有清除板上的方塊。 因此,如果您沿一條潛在路徑遞歸,失敗,然后再嘗試另一條路徑,則即使第一次嘗試仍然會標出方格,因此第二次嘗試也會失敗。
array[x][y] = n;
if ( fill(x+1, y-2, n+1) || fill(x-2, y+1, n+1) || fill(x+1, y+2, n+1)
|| fill(x+2, y+1, n+1) || fill(x-2, y-1, n+1) || fill(x-1, y-2, n+1) ||
fill(x-1, y+2, n+1) || fill(x+2, y-1, n+1))
return true;
else
{
array[x][y] = 0; // <- add this line
return false;
}
問題是,當發生回溯時,您的代碼沒有將位置重置為0,而下一次在另一遍中,它以為它在那里而感到困惑,但是該位置應該已重置。 這是帶有修復程序的代碼片段:
else
{
array[x][y] = n;
if ( fill(x+1, y-2, n+1) || fill(x-2, y+1, n+1) || fill(x+1, y+2, n+1)
|| fill(x+2, y+1, n+1) || fill(x-2, y-1, n+1) || fill(x-1, y-2, n+1) ||
fill(x-1, y+2, n+1) || fill(x+2, y-1, n+1))
return true;
else {
array[x][y] = 0;//NEED THIS LINE
return false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.