添加链接描述
#include<bits/stdc++.h>
using namespace std;
struct pos{
int x,y,step;
};
int to[8][2]={1,2,1,-2,-1,2,-1,-2,2,1,2,-1,-2,1,-2,-1};
int vis[10][10];
int ex,ey;
char s[5],s1[5];
int bfs(){
queue<pos> q;
pos t,nex,sta;
sta.x =s[0]-'a';
sta.y =s[1]-'1';
sta.step =0;
ex=s1[0]-'a';
ey=s1[1]-'1';
memset(vis,0,sizeof vis);
vis[sta.x ][sta.y ]=1;
q.push(sta);
while(!q.empty() ){
t=q.front() ;
q.pop();
if(t.x ==ex&&t.y ==ey){
return t.step ;
}
for(int i=0;i<8;i++){
nex.x =t.x +to[i][0];
nex.y =t.y +to[i][1];
if(nex.x ==ex&&nex.y ==ey){
return t.step +1;
}
if(nex.x >=0&&nex.x <8&&nex.y >=0&&nex.y <8&&vis[nex.x ][nex.y ]==0){
vis[nex.x ][nex.y ]=1;
nex.step =t.step +1;
q.push(nex);
}
}
}
return 0;
}
int main()
{
while(scanf("%s%s",s,s1)!=EOF){
printf("To get from %s to %s takes %d knight moves.\n",s,s1,bfs());
}
return 0;
}