题意:
给定一个8*8的方格中的两个位置,求骑士用象棋中的马字走位要走几次才能到。
思路:
用bfs,从起点开始尝试8个方向的走位,一步步的接近目的地,最后计算步数,注意骑士的终点和起点可以相同。
#include <iostream>
#include<cstring>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int ce[8][8];
int up[8]={2,2,1,1,-2,-2,-1,-1};
int low[8]={-1,1,2,-2,-1,1,-2,2},count;
struct{
int x,y,pre;
}q[1000];
void print(int p){
if(q[p].pre!=-1){
print(q[p].pre);
count++;
}
}
void bfs(int s1,int s2,int e1,int e2){
q[0].pre=-1;
q[0].x=s1;q[0].y=s2;
int bu=0,now=0,nx,ny,fo=1;
while(1){
now=bu;
for(int i=0;i<8;i++){
nx=q[now].x+up[i];
ny=q[now].y+low[i];
if(nx<0||ny<0||nx>7||ny>7||ce[nx][ny])
continue;
else{
ce[nx][ny]=1;
q[fo].pre=bu;
q[fo].x=nx;
q[fo].y=ny;
fo++;
}
if(nx==e1&&ny==e2) {
print(bu);return;
}
}
bu++;
}
}
int main(int argc, char** argv) {
char a[3],b[3];
while(scanf("%s %s",a,b)!=EOF){
if(strcmp(a,b)==0) printf("To get from %c%c to %c%c takes 0 knight moves.\n",a[0],a[1],b[0],b[1]);
else{
memset(ce,0,sizeof(ce));count=1;
bfs(a[0]-'a',a[1]-'1',b[0]-'a',b[1]-'1');
printf("To get from %c%c to %c%c takes %d knight moves.\n",a[0],a[1],b[0],b[1],count);
}
}
return 0;
}