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.
# include<stdio.h>
# include<string.h>
int mark[10][10],x1,y1,x2,y2;
int dir[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
char s1[5],s2[5];
struct node{
int x,y,step;
};
struct node queue[100];
int bfs()
{
int i,head,tail;
struct node cur,next;
head=0;
tail=1;
while(head<tail)
{
cur=queue[head++];
for(i=0;i<8;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
next.step=cur.step+1;
if(next.x>=1&&next.x<=8&&next.y>=1&&next.y<=8&&mark[next.x][next.y]==0)
{
if(next.x==x2&&next.y==y2)
return next.step;
else
{
mark[next.x][next.y]=1;
queue[tail++]=next;
}
}
}
}
return -1;
}
int main()
{
int t;
while(scanf("%s%s",s1,s2)!=EOF)
{
x1=s1[1]-'0';
y1=s1[0]-'a'+1;
x2=s2[1]-'0';
y2=s2[0]-'a'+1;
queue[0].x=x1;
queue[0].y=y1;
queue[0].step=0;
memset(mark,0,sizeof(mark));
if(x1==x2&&y1==y2)
{
t=0;
printf("To get from %s to %s takes %d knight
moves.\n",s1,s2,t);
continue;
}
mark[x1][y1]=1;
t=bfs();
printf("To get from %s to %s takes %d knight
moves.\n",s1,s2,t);
}
return 0;
}