(感觉自己越来越懒了,题目都不用贴了……)
谨以此纪念一下自己学会的第一道BFS~
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct type{
int x,y,step;
}st,ed;
bool s[10][10];
int dir[8][2] = {{-1,+2},{-2,+1},{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2}};
int bfs()
{
queue<type> q;
memset(s,0,sizeof(s));
s[st.x][st.y]=1;
q.push(st);
while(!q.empty())
{
type next,now=q.front();q.pop();
//printf("now: x=%d y=%d step=%d\n",now.x,now.y,now.step);
if(now.x == ed.x && now.y == ed.y) return now.step;
for(int i=0;i<8;i++)
{
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.step=now.step+1;
if(next.x>=1 && next.y>=1 && next.x<=8 && next.y<=8 && s[next.x][next.y]==0)
{
s[next.x][next.y]=1;
q.push(next);
}
}
}
}
int main()
{
char begin[2],end[2];
while(scanf("%c%c %c%c%*c",&begin[0],&begin[1],&end[0],&end[1])!=EOF)
{
st.x=begin[1]-'0';
st.y=begin[0]-'a'+1;
st.step=0;
//printf("st: x=%d y=%d\n",st.x,st.y);
ed.x=end[1]-'0';
ed.y=end[0]-'a'+1;
//printf("ed: x=%d y=%d\n",ed.x,ed.y);
int ans=bfs();
printf("To get from %c%c to %c%c takes %d knight moves.\n",begin[0],begin[1],end[0],end[1],ans);
}
}