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.
#include
#include
#include
#define maxn 10
using namespace std;
int dir[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int visit[maxn][maxn];
int check(int a,int b)
{
if(a<1||a>8||b<1||b>8||visit[a][b])
return 1;
else
return 0;
}
struct node
{
int x,y;
int times;
}start,fr,a;
int bfs(int sx,int sy,int x,int y)
{
memset(visit,0,sizeof(visit));
queue Q;
start.x=sx;
start.y=sy;
start.times=0;
visit[start.x][start.y]=1;
Q.push(start);
while(!Q.empty())
{
fr=Q.front();
Q.pop();
//cout<<"x="<<x<<" "<<"y="<<y<<endl;
if(fr.x==x&&fr.y==y)
return fr.times;
for(int i=0;i<8;i++)
{
a.x=fr.x+dir[i][0];
a.y=fr.y+dir[i][1];
if(check(a.x,a.y))
continue;
a.times=fr.times+1;
visit[a.x][a.y]=1;
Q.push(a);
}
}
int main()
{
//freopen("in.txt", "r", stdin);
char a,b;
int sx,sy,x,y;
while(~scanf("%c%d %c%d\n",&a,&sy,&b,&y))
{
//cout<<"sx="<<a<<endl;
//cout<<"sy="<<sy<<endl;
//cout<<"x="<<b<<endl;
//cout<<"y="<<y<<endl;
sx=a-'a'+1;
x=b-'a'+1;
//坐标转化成数字
int ans=bfs(sx,sy,x,y);
printf("To get from %c%d to %c%d takes %d knight moves.\n",a,sy,b,y,ans);
}
return 0;
}