Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4999 Accepted Submission(s): 3057
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.
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
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 <iostream>
#include <queue>
using namespace std;
int n,m,s,x1,x2,y1,y2,map[11][11],visit[11][11],xx[8][2]={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};
struct ssss
{
int x,y,step;
}ss;
queue<ssss> q,qq;
void bfs()
{
int i,X,x,Y,y,step;
while(!q.empty())
{
ss=q.front();q.pop();
X=ss.x;Y=ss.y;step=ss.step+1;
if(X==x2&&Y==y2){s=ss.step;return;}
for(i=0;i<8;i++)
{
x=X+xx[i][0];
y=Y+xx[i][1];
if(x>0&&y>0&&x<=8&&y<=8&&visit[x][y])
{
visit[x][y]=0;ss.x=x;ss.y=y;ss.step=step;q.push(ss);
}
}
}
}
int main (void)
{
int i,j,k,l;
char c1,c2;
while(cin>>c1>>y1>>c2>>y2)
{
x1=(int)c1-96;x2=(int)c2-96;
for(i=1;i<=8;i++)
for(j=1;j<=8;j++)
visit[i][j]=1;
q=qq;ss.x=x1;ss.y=y1;ss.step=0;s=0;q.push(ss);
bfs();
cout<<"To get from "<<c1<<y1<<" to "<<c2<<y2<<" takes "<<s<<" knight moves."<<endl;
}
return 0;
}