Link:http://acm.hdu.edu.cn/showproblem.php?pid=1372
Problem:
Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6820 Accepted Submission(s): 4116
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<algorithm>
#include<queue>
using namespace std;
int map[9][9];
int sr,sc,er,ec;
int d[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node{
int r;
int c;
int sp;
};
int bfs()
{
queue<node>Q;
memset(map,0,sizeof(map));
node now,next;
int i,ri,ci;
now.c=sc;
now.r=sr;
now.sp=0;
Q.push(now);
map[sr][sc]=1;
while(!Q.empty())
{
now=Q.front();
if(now.c==ec&&now.r==er)
return now.sp;
Q.pop();
for(i=0;i<8;i++)
{
ri=d[i][0]+now.r;
ci=d[i][1]+now.c;
if(ri>=0&&ri<8&&ci>=0&&ci<8&&map[ri][ci]==0)
{
map[ri][ci]=1;
next.c=ci;
next.r=ri;
next.sp=now.sp+1;
Q.push(next);
}
}
}
}
int main()
{
char s1[10],s2[10];
int ans;
while(scanf("%s%s",s1,s2)!=EOF)
{
sc=s1[0]-'a';
sr=s1[1]-'1';
ec=s2[0]-'a';
er=s2[1]-'1';
printf("%d %d %d %d\n",sc,sr,ec,er);
ans=bfs();
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,ans);
}
return 0;
}