原题链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=380
**解题思路:层次遍历。加上两个标志leftNum(当前层剩余的结点个数),
curNum(下一层的结点个数).详细见代码注释。**
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int dx[8]={-2,-1,1,2,2,1,-1,-2};//方向数组
const int dy[8]={1,2,2,1,-1,-2,-2,-1};
char s[4];
int x1,y1,x2,y2;
int visit[8][8];
int bfs(int x,int y){
queue<int>q;
int sx,sy,leftNum=1,curNum=0,cnt=0;
q.push(x*10+y);
visit[x][y]=1;
while(!q.empty()){
x=q.front()/10;
y=q.front()%10;
if(x==x2&&y==y2-1){
break;
}
q.pop();
leftNum--;//当前层剩余结点数减1
for(int i=0;i<8;i++){
sx=x+dx[i];
sy=y+dy[i];
if(!visit[sx][sy]&&sx>=0&&sx<8&&sy>=0&&sy<8){
q.push(sx*10+sy);
visit[sx][sy]=1;
curNum++;//下一层结点数累加
}
}
if(leftNum==0){//剩余结点为0,跳到下一层,更新值。
leftNum=curNum;
curNum=0;
cnt++;
}
}
return cnt;
}
int main(){
//freopen("uva439.txt","r",stdin);
while(scanf("%s",s)==1){
memset(visit,0,sizeof(visit));
x1=s[0]-'a';
y1=s[1]-'0';
//printf("x1==%c y1==%d\n",x1+'a',y1);
scanf("%s",s);
x2=s[0]-'a';
y2=s[1]-'0';
//printf("x2==%c y2==%d\n",x2+'a',y2);
int cnt=bfs(x1,y1-1);//行输入是1-8,需要减1变为0-7
//printf("cnt==%d\n",cnt);
printf("To get from %c%d to %c%d takes %d knight moves.\n",x1+'a',y1,x2+'a',y2,cnt);
}
return 0;
}