you is doing research on the Traveling Knight Problem (TKP) where
you are to find the shortest closed tour of knight moves that
visits each square of a given set of n squares on a chessboard
exactly once. He thinks that the most difficult part of the problem
is determining the smallest number of knight moves between two
given squares and that, once you have accomplished this, finding
the tour would be easy.
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.
will contain one or more test cases. Each test case consists of one
line containing two squares separated by one space. A square is a
string consisting of a letter (a-h) representing the column and a
digit (1-8) representing the row on the chessboard.
case, print one line saying "To get from xx to yy takes n knight
moves.".
e2 to e4 takes 2 knight moves.
a1 to b2 takes 4 knight moves.
b2 to c3 takes 2 knight moves.
a1 to h8 takes 6 knight moves.
a1 to h7 takes 5 knight moves.
h8 to a1 takes 6 knight moves.
b1 to c3 takes 1 knight moves.
f6 to f6 takes 0 knight moves.
#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;
}