广度优先搜索
#include <stdio.h>
#include <string.h>
typedef struct
{
int a, b, cnt;
}POINT;
POINT stack[1000];
int reachable(int x, int y)
{
if(x >= 0 && x <= 7 && y >= 0 && y <= 7) return 1;
return 0;
}
int main(void)
{
char flag[8][8], t1[5], t2[5];
int dir[8][2] = {1, 2, 1, -2, -1, 2, -1, -2, 2, 1, 2, -1, -2, 1, -2, -1};
int x1, y1, x2, y2, head, tail, i;
while(scanf("%s%s", t1, t2) != EOF)
{
x1 = t1[0] - 'a';
y1 = t1[1] - '1';
x2 = t2[0] - 'a';
y2 = t2[1] - '1';
memset(flag, 0, sizeof(flag));
head = 0;
tail = 1;
stack[head].a = x1;
stack[head].b = y1;
stack[head].cnt = 0;
flag[x1][y1] = 1;
while(head < tail)
{
if(stack[head].a == x2 && stack[head].b == y2)
{
printf("To get from %s to %s takes %d knight moves.\n", t1, t2, stack[head].cnt);
break;
}
for(i = 0; i < 8; i++)
{
if(reachable(stack[head].a+dir[i][0], stack[head].b+dir[i][1]) && flag[stack[head].a+dir[i][0]][stack[head].b+dir[i][1]] == 0)
{
flag[stack[head].a+dir[i][0]][stack[head].b+dir[i][1]] = 1;
stack[tail].a = stack[head].a+dir[i][0];
stack[tail].b = stack[head].b+dir[i][1];
stack[tail].cnt = stack[head].cnt + 1;
tail ++;
}
}
head ++;
}
}
return 0;
}