题意:给出两个骑士(骑士走日和中国象棋的马一样如果还不知道自行百度)的位置 求一个到另一个最少要走的步数
思路:常规的广搜题 ,向8个方向搜索。
code:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int to[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
bool map[10][10];
int xx,yy;
char s1[3],s2[3];
struct node
{
int x,y,tt;
};
bool IsOk(int x,int y)
{
if(x<0||y<0||x>=8||y>=8||map[x][y])
return true;
return false;
}
int bfs()
{
node a,next;
queue<node>Q;
a.x=s1[0]-'a';a.y=s1[1]-'1';
a.tt=0;
xx=s2[0]-'a';yy=s2[1]-'1';
memset(map,0,sizeof(map));
map[a.x][a.y]=true;
Q.push(a);
while(!Q.empty()){
a=Q.front();
Q.pop();
if(a.x==xx&&a.y==yy)
return a.tt;
for(int i=0;i<8;i++){
next.x=a.x+to[i][0];
next.y=a.y+to[i][1];
next.tt=a.tt+1;
if(next.x==xx&&next.y==yy)
return next.tt;
if(IsOk(next.x,next.y))
continue;
map[next.x][next.y]=true;
Q.push(next);
}
}
return 0;
}
int main()
{
while(~scanf("%s%s",s1,s2)){
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());
}
return 0;
}