#include <stdio.h>
#include <string.h>
int chessboard[8][8];
char s1[2], s2[2];
int queue[100], top, rear;
int position[8][2] = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};
void bfs(void)
{
int i, x, y, temp1, temp2;
do {
x = queue[top]/10;
y = queue[top]%10;
top++;
top %= 100;
for (i = 0; i < 8; i++) {
temp1 = x+position[i][0];
temp2 = y+position[i][1];
if (temp1 >=0 && temp1 < 8 && temp2 >= 0 && temp2 < 8 && chessboard[temp1][temp2] == -1) {
++rear;
rear %= 100;
queue[rear] = temp1*10 + temp2;
chessboard[temp1][temp2] = x*10+y;
if (temp1 == s2[0]-'a' && temp2 == s2[1]-'1')
return;
}
}
}while (top != rear);
}
int main()
{
int num, n, i, j;
while (scanf("%s%s", s1, s2) == 2) {
top =rear = 0;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
chessboard[i][j] = -1;
chessboard[s1[0]-'a'][s1[1]-'1'] = queue[rear] = (s1[0]-'a')*10 + s1[1]-'1';
num = 0;
if (s1[0] != s2[0] || s1[1] != s2[1]) {
bfs();
num = 1;
}
i = s2[0]-'a';
j = s2[1]-'1';
for (; chessboard[i][j] != (s1[0]-'a')*10 + s1[1]-'1'; num++) {
n = chessboard[i][j];
i = n/10;
j = n%10;
}
printf("To get from %s to %s takes %d knight moves.\n", s1, s2, num);
}
return 0;
}
POJ-2243
最新推荐文章于 2021-08-07 19:27:56 发布