Knight Moves
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 20 Accepted Submission(s) : 10
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.
//進隊後visit數組標記爲true;map數組記錄走的步數,head指向隊頭,tail指向隊尾。
//題目中的column(列)剛好對應到x,row(行)對應到y
#include<cstdio>
#include<cstring>
bool visit[10][10];
int map[10][10];
struct node
{
int x,y;
};
int dir[8][2]={1,2,1,-2,-1,2,-1,-2,2,1,2,-1,-2,1,-2,-1};
node que[100];
int BFS(node s,node t)
{
if(s.x==t.x&&s.y==t.y) return 0;
int head=0,tail=0;
que[tail++]=s;
visit[s.x][s.y]=true;
node tt;
while(head<tail)
{
tt=que[head++];
for(int i=0;i<8;i++)
{
node ss;
ss.x=tt.x+dir[i][0];
ss.y=tt.y+dir[i][1];
cnt++;
if(ss.x>=1&&ss.x<=8&&ss.y>=1&&ss.y<=8&&!visit[ss.x][ss.y])
{
map[ss.x][ss.y]=map[tt.x][tt.y]+1;
if(ss.x==t.x&&ss.y==t.y) return map[ss.x][ss.y];
que[tail++]=ss;
visit[ss.x][ss.y]=true;
}
}
}
}
int main()
{
char c1,c2,c;
node st,ed;
while(scanf("%c%d%c%c%d",&c1,&st.y,&c,&c2,&ed.y)!=EOF)//8row 8column
{
getchar();
memset(visit,false,sizeof(visit));
memset(map,0,sizeof(map));
st.x=c1-'a'+1;
ed.x=c2-'a'+1;
cnt=0;
printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,st.y,c2,ed.y,BFS(st,ed));
}
return 0;
}