题目描述
小明很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。
提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。
输入描述
输入包含多组测试数据。每组输入由两个方格组成,每个方格包含一个小写字母(a~h),表示棋盘的列号,和一个整数(1~8),表示棋盘的行号。
输出描述
对于每组输入,输出一行“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 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.
简单的bfs
#include"iostream"
#include"string.h"
#include"queue"
using namespace std;
int stah,stal;
int resh,resl;
char lie1,lie2;
bool sign[10][10];
int fx[8][2]={2,1,2,-1,1,2,1,-2,-2,1,-2,-1,-1,-2,-1,2};
struct node
{
int x,y,step;
};
bool check(int a,int b)
{
if(a>=1&&a<=8&&b>=1&&b<=8&&!sign[a][b])
return true;
return false;
}
void bfs()
{
node mm,nn;
mm.x=stah; mm.y=stal; mm.step=0;
sign[stah][stal]=true;
queue<node> jj;
jj.push(mm);
while(!jj.empty())
{
nn=jj.front();
jj.pop();
if(nn.x==resh&&nn.y==resl)
{
cout<<"To get from "<<lie1<<stah<<" to "<<lie2<<resh<<" takes "<<nn.step<<" knight moves."<<endl;
return ;
}
for(int i=0;i<8;i++)
{
mm=nn;
mm.x+=fx[i][0];
mm.y+=fx[i][1];
if(check(mm.x,mm.y))
{
mm.step++;
sign[mm.x][mm.y]=true;
jj.push(mm);
}
}
}
}
int main()
{
while(cin>>lie1>>stah)
{
stal=lie1-'a'+1;
cin>>lie2>>resh;
resl=lie2-'a'+1;
memset(sign,0,sizeof(sign));
bfs();
}
return 0;
}