1372
标准的bfs做法,注意这个棋是走“日”字
#include<bits/stdc++.h>
using namespace std;
//这题需要注意棋子走法
int t[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
int mep[15][15],X,Y;
char s1[10],s2[10];
struct node{
int x,y,step;
};
int check(int a,int b){//是否需要访问
if(a<0||b<0||a>=8||b>=8||mep[a][b])return 1;//不需要,走过了/不能走
return 0;
}
int bfs(){
queue<node>Q;
node p,q,next;
p.x=s1[0]-'a';//列
p.y=s1[1]-'1';//行
p.step=0;
X=s2[0]-'a';
Y=s2[1]-'1';
memset(mep,0,sizeof(mep));
mep[p.x][p.y]=1;
Q.push(p);
while(!Q.empty()){
q=Q.front();
Q.pop();
if(q.x==X&&q.y==Y)return q.step;
for(int i=0;i<8;i++){
next.x=q.x+t[i][0];
next.y=q.y+t[i][1];
if(next.x==X&&next.y==Y)return q.step+1;//接下来可以走到
if(check(next.x,next.y))continue;//此路不通
next.step=q.step+1;
mep[next.x][next.y]=1;
Q.push(next);
}
}
return 0;//失败了,走不到
}
int main(){
while(cin>>s1>>s2){
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());
}
return 0;
}