hdu 1372 Knight Moves
走的是日。。。
#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
int dir[8][2]={{-2,1},{2,-1},{-1,2},{1,-2},{-1,-2},{-2,-1},{1,2},{2,1}};
int map[10][10];
int ex,ey,sx,sy;
struct node
{
int x,y,step;
};
int bfs()
{
queue<node>Q;
node q,p;
int x,y,i;
p.x=sx;
p.y=sy;
p.step=0;
map[sx][sy]=1;
Q.push(p);
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(p.x==ex&&p.y==ey)
return p.step;
for(i=0;i<8;i++)
{
q.x=x=p.x+dir[i][0];
q.y=y=p.y+dir[i][1];
q.step=p.step+1;
if(x>=0&&x<8&&y>=0&&y<8&&map[x][y]==0)
{
map[x][y]=1;
Q.push(q);
}
}
}
}
int main()
{
char s1[3],s2[3];
while(scanf("%s %s",s1,s2)!=EOF)
{
memset(map,0,sizeof(map));
sx=s1[0]-'a';
sy=s1[1]-'1';
ex=s2[0]-'a';
ey=s2[1]-'1';
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());
}
return 0;
}
浙公网安备 33010602011771号