原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1372
题目大意:
横坐标为a~h
纵坐标为1~8
求从A位置到B位置所走的最少步数。
走的方式为中国象棋中马的八种方式。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN=9;
int G[MAXN][MAXN];
bool flog[MAXN][MAXN];//标记
const int nextr[]={-2,-2,-1,+1,+2,+2,+1,-1};//8个方向
const int nextc[]={-1,+1,+2,+2,+1,-1,-2,-2};
const char base='a'-1;
int c1,c2;
char r1,r2;
struct g
{
int r,c;
int step;
};
bool check(int r,int c)//判断能否走到下一步
{
if(r<1||r>8||c<1||c>8||flog[r][c])
return false;
return true;
}
int BFS()
{
queue<g>q;
g pos;
pos.r=r1-base;
pos.c=c1;
pos.step=0;
flog[pos.r][pos.c]=true;
q.push(pos);
while(!q.empty())
{
pos=q.front();
q.pop();
if(pos.r==r2-base&&pos.c==c2) return pos.step;
for(int i=0;i<8;i++)
{
g temp;
temp.r=pos.r+nextr[i];
temp.c=pos.c+nextc[i];
temp.step=pos.step+1;
if(check(temp.r,temp.c))
q.push(temp);
}
}
}
int main()
{
while(scanf("%c%d%*c%c%d",&r1,&c1,&r2,&c2)!=EOF)
{
//cout<<r1<<c1<<r2<<c2<<endl;
memset(flog,0,sizeof(flog));
printf("To get from %c%d to %c%d takes %d knight moves.\n",r1,c1,r2,c2,BFS());
getchar();
}
return 0;
}