题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
题目不难,但我看完题目是懵逼的,还是要懂点国际象棋才可以的。
#include <stdio.h>
#include <string.h>
typedef struct
{
int x,y,step;
} node;
node queue[100];
int map[10][10];
int next[8][2] = {-2,1, -1,2, 1,2, 2,1, 2,-1, 1,-2, -1,-2, -2,-1};//方向
int startx,starty,endx,endy;
int main()
{
char a[3],b[3];
int head,tail,flag,k,tx,ty;
while(scanf("%s %s",a,b) != EOF)
{
flag = head = tail = 0;
startx = a[0] - 'a' + 1;
starty = a[1] - '0';
endx = b[0] - 'a' + 1;
endy = b[1] - '0';
memset(map,0,sizeof(map));//初始化棋盘
queue[tail].x = startx;//起点入队
queue[tail].y = starty;
queue[tail].step = 0;
tail++;
map[startx][starty] = 1;
while(head < tail)
{
if(queue[head].x == endx && queue[head].y == endy)
{
flag = 1;
break;
}
for(k = 0; k < 8; ++k)
{
tx = queue[head].x + next[k][0];
ty = queue[head].y + next[k][1];
if(tx < 1 || ty < 1 || tx > 8 || ty > 8)
continue;
if(map[tx][ty] == 0)
{
map[tx][ty] = 1;//标记
queue[tail].x = tx;//入队
queue[tail].y = ty;
queue[tail].step = queue[head].step + 1;
tail++;
}
}
head++;
}
if(flag)
printf("To get from %s to %s takes %d knight moves.\n",a,b,queue[head].step);
}
return 0;
}