題目來源:http://acm.hdu.edu.cn/vcontest/vtl/problem/showproblem/vtlid/4642/problemid/1011
java代碼如下:
public class Shortest {
//http://acm.hdu.edu.cn/vcontest/vtl/problem/showproblem/vtlid/4642/problemid/1011
private int[][] table=new int[10][10];
private boolean[][] map=new boolean[10][10];
private void initTable(){
int i=5;
int j=4;
int number=2;
table[i][j]=1;
int a=1,b=2;
while(number<73){
for(int d=0;d<a;d++){
table[i][++j]=number++;
}
for(int d=0;d<a;d++){
table[--i][j]=number++;
}
a+=2;
for(int d=0;d<b;d++){
table[i][--j]=number++;
}
for(int d=0;d<b;d++){
table[++i][j]=number++;
}
b+=2;
}
for(int d=0;d<a;d++){
table[i][++j]=number++;
}
for(int d=0;d<a;d++){
table[--i][j]=number++;
}
for(int d=0;d<b-1;d++){
table[i][--j]=number++;
}
}
private void initMap(){
map[0][3]=true;
map[1][4]=map[1][6]=true;
map[2][1]=map[2][7]=map[2][9]=true;
map[3][0]=map[3][2]=map[3][6]=true;
map[4][3]=map[4][5]=map[4][7]=true;
map[5][2]=map[5][5]=map[5][6]=map[5][8]=true;
map[6][1]=map[6][3]=true;
map[7][0]=map[7][4]=true;
map[8][1]=map[8][5]=map[8][9]=true;
map[9][0]=map[9][6]=true;
}
private int aim;
public Shortest(int a,int b){
initTable();
initMap();
aim=b;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++){
if(table[i][j]==a){
process(i,j,0);
break;
}
}
if(bestPath==1000000){
System.out.println("impossible");
}else{
System.out.println(bestPath);
}
}
//表示很遠
private int bestPath=1000000;
private void process(int i,int j,int path){
if(table[i][j]==aim){
if(path<bestPath){
bestPath=path;
}
}
map[i][j]=true;
//沒有數據 有數據的爲true,
if(i-1>=0&&!map[i-1][j]){
//向上
process(i-1,j,path+1);
}
if(i+1<=9&&!map[i+1][j]){
//向下
process(i+1,j,path+1);
}
if(j-1>=0&&!map[i][j-1]){
//向左
process(i,j-1,path+1);
}
if(j+1<=9&&!map[i][j+1]){
//向右
process(i,j+1,path+1);
}
map[i][j]=false;
}
public static void main(String[] args) {
int start=9;
int end=32;
new Shortest(start,end);
}
}