基础宽搜,写在这儿的目的是提醒自己慎用 ~
输入的时候老是喜欢写 while(~scanf()) 这下好了,C++就要TLE,改成While(scanf()!=EOF)就AC了。
G++ 到时无所谓。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>
#define INF 0x7fffffff
using namespace std;
struct lx
{
int x,y;
int lv;
};
lx start,thend;
int xx[]={-2,-2,-1,-1,1,1,2,2};
int yy[]={1,-1,2,-2,2,-2,1,-1};
bool vis[10][10];
int bfs()
{
queue<lx>q;
lx tmp;
memset(vis,0,sizeof(vis));
start.lv=0;
q.push(start);
vis[start.x][start.y]=1;
while(!q.empty())
{
tmp=q.front();q.pop();
vis[tmp.x][tmp.y]=1;
if(tmp.x==thend.x&&tmp.y==thend.y)
return tmp.lv;
for(int k=0;k<8;k++)
{
int x=tmp.x+xx[k];
int y=tmp.y+yy[k];
if(x>8||x<1||y>8||y<1||vis[x][y])continue;
lx now;
now.x=x,now.y=y,now.lv=tmp.lv+1;
q.push(now);
}
}
return -1;
}
int main()
{
char sa[3],sb[3];
while(scanf("%s%s",sa,sb)!=EOF)
{
start.x=sa[0]-'a'+1;
start.y=sa[1]-'0';
thend.x=sb[0]-'a'+1;
thend.y=sb[1]-'0';
int tp=bfs();
printf("To get from %s to %s takes %d knight moves.\n",sa,sb,tp);
}
return 0;
}