#include <cstdio>
#include <cstdlib>
#include <cstring>
#define local
int vis[8][8]; //遍历标志,已被访问的标为1
int dist[8][8]; //长度
//int fa[8][8];
int q[100];
int dx[8]={1,2,2,1,-1,-2,-2,-1}; //dx dy为骑士的步法
int dy[8]={2,1,-1,-2,-2,-1,1,2};
void bfs(int x,int y,int x1,int y1) //起点(x,y)终点(x1,y1)
{
int front=0,rear=0,d,u;
u=8*x+y; //把坐标转换为一个值,一个坐标对应一个值
vis[x][y]=1;dist[x][y]=0;
q[rear++]=u;
while(front<rear)
{
u=q[front++];x=u/8;y=u%8;
for(d=0;d<8;d++)
{
int nx=x+dx[d],ny=y+dy[d];
if(nx>=0&&nx<8&&ny>=0&&ny<8&&!vis[nx][ny])
{
int v=nx*8+ny;
q[rear++]=v; //子节点入队列
vis[nx][ny]=1;
dist[nx][ny]=dist[x][y]+1;
if(nx==x1&&ny==y1){return;} //到达终点(x1,y1)
}
}
}
}
int main()
{
#ifdef local
freopen("d.in","r",stdin);
freopen("d.out","w",stdout);
#endif
char a[3],b[3];
while(scanf("%s%s",a,b)!=EOF)
{
memset(vis,0,sizeof(vis));
memset(q,0,sizeof(q));
memset(dist,0,sizeof(dist));
int x1,y1,x2,y2;
x1=a[0]-'a';y1=a[1]-'0'-1;
x2=b[0]-'a';y2=b[1]-'0'-1;
// x=(x2>x1)?x2-x1:x1-x2;
// y=(y2>y1)?y2-y1:y1-y2;
bfs(x1,y1,x2,y2);
printf("To get from %s to %s takes %d knight moves.\n",a,b,dist[x2][y2]);
//printf("(%d,%d) (%d,%d)\n",x1,y1,x2,y2);
}
return 0;
}
ACMer菜鸟第一次做图论的题目,参考刘汝佳的算法书.