`

恒生电子的一道编程题

    博客分类:
  • java
 
阅读更多

题目:4*8的一块格子,设x为0-8,y为0-4;按照象棋中‘马’的步伐走,即能从(0,0)走到(1,2)或者(2,1)。

假设只能朝x增大的方向走,不能回头,一直走到x=8,输出所有可能的路线。

 

我写的一种 递归方法,请大家给点意见

 

public class Cheese{

 

static int index=0;

static String location[]=new String[9];

 

 

public static void jumpTo(int x,int y){

if(x==8){

for(int i=0;i<=index;i++){System.out.print(location[i]);}

System.out.println();

 

}else{

if(y+2<=4){index++;    location[index]="("+(x+1)+","+(y+2)+")";    jumpTo(x+1,y+2);   index--;}

if(y-2>=0){index++;    location[index]="("+(x+1)+","+(y-2)+")";      jumpTo(x+1,y-2);    index--;}

 

if(x+2<=8){

 

if(y+1<=4){index++;   location[index]="("+(x+2)+","+(y+1)+")";     jumpTo(x+2,y+1);   index--;}

if(y-1>=0){index++;    location[index]="("+(x+2)+","+(y-1)+")";      jumpTo(x+2,y-1);    index--;}

 

          }

 

}

}

 

 

public static void main(String[] args){

location[0]="(0,0)";

jumpTo(0,0);

 

}

 

 

 

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics