For each test case, print one line saying "To get from xx to yy takes n knight moves.".
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6Sample Output
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.题解
一个8*8的棋盘,骑士的每一步其实是象棋中马的走法,有8个方向。不论骑士在哪都能走到目标点。注意用字母是列,数字是行,转化为(x,y)会方便一些。BFS直接过。
代码
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct node
{
int x;
int y;
}now,ne,en;
int main()
{
char a[5]={0},b[5]={0};
while(~scanf("%s %s",a,b))
{
if(!strcmp(a,b))
{
printf("To get from %s to %s takes 0 knight moves.\n",a,b);
continue;
}//相等情况直接输出
int i,j,use[9][9]={0},count=0;;
int dir[8][2]={2,1,2,-1,-2,1,-2,-1,1,-2,1,2,-1,2,-1,-2};//8个方向
queue<node> qu;
en.x=b[1]-48;
en.y=b[0]-96;
now.x=a[1]-48;
now.y=a[0]-96;//转化坐标
use[now.x][now.y]=1;
qu.push(now);
for(;;)//BFS
{
int flag=0,l=qu.size();
count++;
while(l--)
{
now=qu.front();
qu.pop();
for(i=0;i<8;i++)
{
ne.x=now.x+dir[i][0];
ne.y=now.y+dir[i][1];
if(use[ne.x][ne.y]==0&&ne.x>0&&ne.x<9&&ne.y>0&&ne.y<9)//剪枝要恰好合适,不然步数会错
{
if(en.x==ne.x&&en.y==ne.y)
{
printf("To get from %s to %s takes %d knight moves.\n",a,b,count);
flag=1;
}
else
{
qu.push(ne);
use[ne.x][ne.y]=1;
}
}
if(flag)break;
}
if(flag)break;
}
if(flag)break;
}
}
}