[英]knight's tour : not able to resolve
我寫了這段代碼來打印一個可能的騎士之旅,以便每個地方都被精確訪問一次。
public class Main{
static int move[][]=new int[8][8];
static int X[]={1 , 2 , 2 , 1 ,-1 ,-2 ,-2,-1};
static int Y[]={2 , 1 ,-1 ,-2 ,-2 ,-1 , 1, 2};
static boolean printMove(int x,int y,int step){
if(step==65){
return true;
}
else{
int x1,y1;
for(int l=0;l<8;l++){
x1=x+X[l];
y1=y+Y[l];
if(x1<8&&y1<8&&x1>=0&&y1>=0&&move[x1][y1]==0){
move[x1][y1]=step;
if(printMove(x1,y1,step+1)){
return true;
}
else
move[x1][y1]=0;
}
}
return false;
}
}
static void printSteps(){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
System.out.print(move[i][j]+" ");
}
System.out.println();
}
}
public static void main(String args[]){
move[0][0]=1;
printMove(0,0,2);
printSteps();
}
}
此代碼有效,但以下代碼無效,我對X []和Y []所做的改動很小,不會影響算法。
public class Main{
static int move[][]=new int[8][8];
static int X[]={-1, 1 , 2 , 2 , 1 ,-1 ,-2 ,-2};
static int Y[]={ 2, 2 , 1 ,-1 ,-2 ,-2 ,-1 , 1};
static boolean printMove(int x,int y,int step){
if(step==65){
return true;
}
else{
int x1,y1;
for(int l=0;l<8;l++){
x1=x+X[l];
y1=y+Y[l];
if(x1<8&&y1<8&&x1>=0&&y1>=0&&move[x1][y1]==0){
move[x1][y1]=step;
if(printMove(x1,y1,step+1)){
return true;
}
else
move[x1][y1]=0;
}
}
return false;
}
}
static void printSteps(){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
System.out.print(move[i][j]+" ");
}
System.out.println();
}
}
public static void main(String args[]){
move[0][0]=1;
printMove(0,0,2);
printSteps();
}
}
我剛換
static int X[]={1 , 2 , 2 , 1 ,-1 ,-2 ,-2,-1};
static int Y[]={2 , 1 ,-1 ,-2 ,-2 ,-1 , 1, 2};
至
static int X[]={-1, 1 , 2 , 2 , 1 ,-1 ,-2 ,-2};
static int Y[]={ 2, 2 , 1 ,-1 ,-2 ,-2 ,-1 , 1};
我懷疑發生的是您的第二個程序實際上正常工作。 這兩個程序都使用蠻力搜索,效率極低,但是第一個程序碰巧很快就絆倒了,而第二個程序卻沒有。
嘗試以下代碼-與您的代碼完全相同,但是會打印進度。 在我看來,它實際上正在工作,花了很長時間才能解決所有其他選擇。
static int move[][] = new int[8][8];
//static int X[]={1 , 2 , 2 , 1 ,-1 ,-2 ,-2,-1};
//static int Y[]={2 , 1 ,-1 ,-2 ,-2 ,-1 , 1, 2};
static int X[]={-1, 1 , 2 , 2 , 1 ,-1 ,-2 ,-2};
static int Y[]={ 2, 2 , 1 ,-1 ,-2 ,-2 ,-1 , 1};
static boolean printMove(int x, int y, int step, String stack) {
if (step == 65) {
return true;
} else {
int x1, y1;
for (int l = 0; l < 8; l++) {
System.out.println(stack+" step = "+step+" l = "+l);
x1 = x + X[l];
y1 = y + Y[l];
if (x1 < 8 && y1 < 8 && x1 >= 0 && y1 >= 0 && move[x1][y1] == 0) {
move[x1][y1] = step;
if (printMove(x1, y1, step + 1, stack + "," + l)) {
return true;
} else {
move[x1][y1] = 0;
}
}
}
return false;
}
}
static void printSteps() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(move[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws InterruptedException {
try {
Test test = new Test();
test.test();
move[0][0] = 1;
printMove(0, 0, 2, "");
printSteps();
} catch (Exception e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.