hdu1372: http://acm.hdu.edu.cn/showproblem.php?pid=1372
题意:一张8*8棋盘,横坐标用a~h表示,纵坐标用1~8表示,每对数据给出马的初始位置和目标位置,问需要多少步能到达
code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
int dx[]={-2,2,-1,1,-2,2,-1,1};
int dy[]={1,-1,-2,-2,-1,1,2,2};
int q[100],vis[10][10],ans[10][10];
const int inf=1<<29;
char w1[2],w2[2];
int min(int i,int j)
{
if(i<j)
return i;
else
return j;
}
int main()
{
int i,j,rear,front,x1,x2,nx,ny,v,y1,y2,u1,u2,x,y,u;
while(scanf("%s%s",w1,w2)!=EOF)
{
memset(vis,0,sizeof(vis));
x1=w1[0]-49-'0';
y1=w1[1]-'0'-1;
x2=w2[0]-49-'0';
y2=w2[1]-'0'-1;
if(x1==x2&&y1==y2)
{
printf("To get from %s to %s takes 0 knight moves.\n",w1,w2);
continue;
}
u1=8*x1+y1;u2=8*x2+y2;
rear=0;front=0;
q[rear++]=u1;
ans[x1][y1]=0;vis[x1][y1]=1;
while(rear>front)
{
u=q[front++];
x=u/8,y=u%8;
for(i=0;i<8;i++)
{
nx=x+dx[i];ny=y+dy[i];
if(nx>=0&&nx<=7&&ny>=0&&ny<=7&&!vis[nx][ny])
{
v=nx*8+ny;vis[nx][ny]=1;
ans[nx][ny]=ans[x][y]+1;
q[rear++]=v;
}
}
}
printf("To get from %s to %s takes %d knight moves.\n",w1,w2,ans[x2][y2]);
}
}
/*
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
*/