【链接】nbu1011点击打开链接
【题目】
骑士的任务
Time Limit:1000MS Memory Limit:65536K
Description
一天骑士Jon接到国王陛下的命令,命他从所在的a点出发,以最短的路径至b点平定叛乱。这里我们假设a点与b点都在8*8的国际象棋棋盘内。骑士Jon所能走的方式为国际象棋中马的行走方式即“日”字形。你的任务是帮助Jon用最短的步数赶到b点。
Input
每一行以坐标形式输入横轴为1,2,3,……,8的数字,纵轴为a,b,……,H的英文字母。第一个坐标是骑士所在的a 点,一个空格之后跟着的是b点的坐标.
以输入0 0结束.
Output
输出你找到的最短步数S。
并用以下格式:
To get from a1 to a1 takes S knight moves.
Sample Input
a1 a1 a1 c2 b2 b3 a1 h8 0 0
Sample Output
To get from a1 to a1 takes 0 knight moves. To get from a1 to c2 takes 1 knight moves. To get from b2 to b3 takes 3 knight moves. To get from a1 to h8 takes 6 knight moves.
Hint
有多组测试数据
【代码】
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
typedef struct ss
{
int x,y,step;
}S;
queue<S> Q;
S p,q;
int mark[65][65];
int f(int x2,int y2)
{
while(!Q.empty())
{
p=Q.front();
Q.pop();
p.step++;
q=p;
if(p.x==x2&&p.y==y2) return p.step;
else
{
if(p.x+1<=8&&p.y+2<=8&&!mark[p.x+1][p.y+2])
{
q.x=p.x+1;
q.y=p.y+2;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x+2<=8&&p.y+1<=8&&!mark[p.x+2][p.y+1])
{
q.x=p.x+2;
q.y=p.y+1;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x-1>=1&&p.y+2<=8&&!mark[p.x-1][p.y+2])
{
q.x=p.x-1;
q.y=p.y+2;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x-2>=1&&p.y+1<=8&&!mark[p.x-2][p.y+1])
{
q.x=p.x-2;
q.y=p.y+1;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x+2<=8&&p.y-1>=1&&!mark[p.x+2][p.y-1])
{
q.x=p.x+2;
q.y=p.y-1;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x+1<=8&&p.y-2>=1&&!mark[p.x+1][p.y-2])
{
q.x=p.x+1;
q.y=p.y-2;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x-1>=1&&p.y-2>=1&&!mark[p.x-1][p.y-2])
{
q.x=p.x-1;
q.y=p.y-2;
mark[q.x][q.y]=1;
Q.push(q);
}
if(p.x-2>=1&&p.y-1>=1&&!mark[p.x-2][p.y-1])
{
q.x=p.x-2;
q.y=p.y-1;
mark[q.x][q.y]=1;
Q.push(q);
}
}
}
}
int main()
{
char a[3],b[3];
int x1,y1,x2,y2,s;
while(scanf("%s%s",a,b)!=EOF)
{
if(strcmp(a,"0")==0&&strcmp(b,"0")==0) break;
x1=a[1]-'0';y1=a[0]-'a'+1;x2=b[1]-'0';y2=b[0]-'a'+1;
memset(mark,0,sizeof(mark));
while(!Q.empty()) Q.pop();
p.x=x1;p.y=y1;p.step=-1;mark[x1][y1]=1;
Q.push(p);
s=f(x2,y2);
printf("To get from %s to %s takes %d knight moves.\n",a,b,s);
}
return 0;
}