题意:
棋盘(a-h)*(1-8),输入起始位置,和终点位置,输出,骑士至少走几步可以从起始位置到达终点位置。(骑士走路方式和马走日一致)
思路:
BFS
注意字母表示列,数字表示行。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N=505;
int dir[][2]={
-1,-2,
1,-2,
2,-1,
2,1,
1,2,
-1,2,
-2,-1,
-2,1
};
bool vis[10][10];
struct node{
int x,y,step;
}s,t;
int bfs(){
queue<node>q;
q.push(s);
vis[s.x][s.y]=1;
while(!q.empty()){
auto e=q.front();
q.pop();
if(e.x==t.x&&e.y==t.y) return e.step;
for(int i=0;i<8;++i){
int nx=e.x+dir[i][0],ny=e.y+dir[i][1];
if(!vis[nx][ny]&&nx>0&&nx<=8&&ny>0&&ny<=8){
if(nx==t.x&&ny==t.y) return e.step+1;
q.push({nx,ny,e.step+1});
vis[nx][ny]=1;
}
}
}
}
int main(){
char S[3],T[3];
while(cin>>S>>T){
s.x=S[1]-'0',s.y=S[0]-'a'+1,s.step=0;
t.x=T[1]-'0',t.y=T[0]-'a'+1;
memset(vis,0,sizeof vis);
printf("To get from %s to %s takes %d knight moves.\n",S,T,bfs());
}
return 0;
}