Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3740 Accepted Submission(s): 2326
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
直接简单的 BFS
#include<stdio.h>
int la_x,la_y;
int flag[9][9];
int Stack[65][2];
int con[65];
int ss[8][2]={ 1, 2,
1,-2,
-1, 2,
-1,-2,
2, 1,
2,-1,
-2, 1,
-2,-1};
int is_(int x)
{
if(x>=1 && x<=8)
return 1;
return 0;
}
int bfs(int st_x,int st_y)
{
int base=0,top=1;
Stack[0][0]=st_x;
Stack[0][1]=st_y;
flag[st_x][st_y]=1;
con[0]=0;
while(base<top)
{
int i;
if(Stack[base][0]==la_x && Stack[base][1]==la_y)
return con[base];
for(i=0;i<8;i++)
{
int a=Stack[base][0]+ss[i][0];
int b=Stack[base][1]+ss[i][1];
if( is_(a) && is_(b) && !flag[a][b])
{
flag[a][b]=1;
con[top]=con[base]+1;
Stack[top][0]=a;
Stack[top++][1]=b;
}
}
base++;
}
return -1;
}
int main(void)
{
int d1,d2;
char c1,c2;
while(scanf("%c%d %c%d",&c1,&d1,&c2,&d2)==4)
{
int i,j;
for(i=1;i<=8;i++)
for(j=1;j<=8;j++)
flag[i][j]=0;
getchar();
la_y=c2-'a'+1;
la_x=d2;
printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,d1,c2,d2,bfs(d1,c1-'a'+1));
}
return 0;
}
7245



被折叠的 条评论
为什么被折叠?



