#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=8+2;
struct node{
int x,y;
node(int x=0,int y=0):x(x),y(y){}
};
node ns,nt;
int d[maxn][maxn];
int dir[][2]={{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1}};
bool isValid(node & nd){
return nd.x>=1 && nd.x<=8 && nd.y>=1 && nd.y<=8;
}
int bfs(){
memset(d,0,sizeof(d));
queue<node>q;
q.push(ns);
while(!q.empty()){
node u=q.front();
q.pop();
if(u.x==nt.x && u.y==nt.y)return d[u.x][u.y];
for(int i=0;i<8;i++){
node v=node(u.x+dir[i][0],u.y+dir[i][1]);
if(isValid(v) && !d[v.x][v.y]){
q.push(v);
d[v.x][v.y]=d[u.x][u.y]+1;
}
}
}
}
int main(){
char s1[2],s2[2];
while(scanf("%s%s",s1,s2)==2){
ns.x=s1[0]-'a'+1;ns.y=s1[1]-'0';
nt.x=s2[0]-'a'+1;nt.y=s2[1]-'0';
int step=bfs();
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,step);
}
return 0;
}
UVA 439 骑士(Knight Moves ) 很基础的BFS
最新推荐文章于 2022-01-24 11:26:32 发布