题意:8X8的棋盘,给两个点,求最短。
题解:BFS
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int vis[30][30];
int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};
struct node{
int x,y,step;
}a,b;
int check(node a){
if(a.x>8||a.x<1||a.y>8||a.y<1)return 0;
if(vis[a.x][a.y])return 0;
return 1;
}
int bfs(){
queue<node>que;
a.step=0;
int i;
node ne;
que.push(a);
while(!que.empty()){
a=que.front();
if(a.x==b.x&&a.y==b.y)return a.step;
que.pop();
for(i=0;i<8;i++){
ne.x=a.x+dir[i][1];
ne.y=a.y+dir[i][0];
ne.step=a.step+1;
if(check(ne)){que.push(ne);vis[ne.x][ne.y]=1;}
}
}
return -1;
}
int main()
{
int m,n;
char c,d;
while(~scanf("%c%d %c%d",&c,&m,&d,&n)){
getchar();
memset(vis,0,sizeof(vis));
a.x=c-'a'+1;
a.y=m;
b.x=d-'a'+1;
b.y=n;//两点
int ans=bfs();
printf("To get from %c%d to %c%d takes %d knight moves.\n",c,m,d,n,ans);
}
return 0;
}