Description
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
The input will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output
For each test case, print one line saying "To get from xx to yy takes n knight moves.".
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.
代码如下:
#include<stdio.h>
#define max 1000000
int Map[8][2] =
{
{-2, 1},
{-1, 2},
{1, 2},
{2, 1},
{2, -1},
{1, -2},
{-1, -2},
{-2, -1}};
//这里将数组代替队列,如果需要,可以变通为滚动数组,当下标达到极限时在置为0
struct N
{
int r, c, k;
}N[max];
int s[9][9];
int Find()
{
int k, h, j, i, x, y;
h = 0;
j = 1;
x = N[h].r;
y = N[h].c;
if (s[x][y] == 2)
{
return N[h].k;
}
while (1)
{
for (i = 0; i < 8; i++)
{
x = N[h].r + Map[i][0];
y = N[h].c + Map[i][1];
if (x >= 0 && x < 8 && y >=0 && y < 8)
{
if (s[x][y] == 2)
{
return N[h].k + 1;
}
else if (s[x][y] == 0)
{
N[j].r = x;
N[j].c = y;
s[x][y] = 1;// 将被扫过的点置为1,我因检查少写了该句被RE了n次
N[j].k = N[h].k + 1;
j++;
}
}
}
h++;
}
};
int main()
{
char ch[2][5];
int i, j, l1, l2, k, r1, r2;
while (scanf("%s %s", ch[0], ch[1]) != EOF)
{
for (i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
{
s[i][j] = 0;
}
}
//将输入的点转为一个二维数组的下标
l1 = ch[0][0] - 'a';
l2 = ch[1][0] - 'a';
r1 = ch[0][1] - '1';
r2 = ch[1][1] - '1';
s[r1][l1] = 1;//1 表示起点
s[r2][l2] = 2;//2 表示终点
N[0].r = r1;
N[0].c = l1;
N[0].k = 0; //k 用于记录当前广度(层数)
k = Find();
printf("To get from %s to %s takes %d knight moves.\n", ch[0], ch[1], k);
}
system("pause");
return 0;
}