Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6439 Accepted Submission(s): 3886
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.
<span style="font-size:24px;">#include<iostream>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
struct node
{
int x,y,num;
};
int a1,a2,b1,b2;
char c1,c2;
int move[8][2]={-2,1,-2,-1,-1,2,-1,-2,1,-2,1,2,2,1,2,-1},v[9][9];
void bfs(int i,int j)
{
node now,temp;
queue<node>q;
now.x=i;
now.y=j;
now.num=0;
memset(v,0,sizeof(v));
q.push(now);
v[now.x][now.y]=1;
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x==b2&&now.y==a2)
{
printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,a1,c2,a2,now.num);
return ;
}
for(int t=0;t<8;t++)
{
temp.x=now.x+move[t][0];
temp.y=now.y+move[t][1];
if(temp.x>0&&temp.x<9&&temp.y>0&&temp.y<9&&!v[temp.x][temp.y])
{
v[temp.x][temp.y]=1;
temp.num=now.num+1;
q.push(temp);
}
}
}
}
int main()
{
while(cin>>c1>>a1>>c2>>a2)
{
b1=c1-'a'+1;
b2=c2-'a'+1;
bfs(b1,a1);
}
return 0;
}</span>