这题跟北大1915题很像,怀疑是从北大抄过来的……
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXL 20
typedef struct {
int x;
int y;
int step;
} MyPoint;
MyPoint start;
int endx, endy, L = 8;
bool visited[MAXL][MAXL];
int move[8][2] = { { 2, 1 }, { 2, -1 }, { -2, 1 }, { -2, -1 }, { 1, 2 },
{ 1, -2 }, { -1, 2 }, { -1, -2 } };
int BFS() {
int i;
queue<MyPoint> Q;
Q.push(start);
memset(visited, 0, sizeof(visited));
visited[start.x][start.y] = true;
MyPoint cur, temp;
while (!Q.empty()) {
cur = Q.front();
Q.pop();
if (cur.x == endx && cur.y == endy) {
return cur.step;
}
temp.step = cur.step + 1;
for (i = 0; i < 8; i++) {
temp.x = cur.x + move[i][0];
temp.y = cur.y + move[i][1];
if (visited[temp.x][temp.y]) {
continue;
}
if (temp.x >= 0 && temp.x < L && temp.y < L && temp.y >= 0) {
visited[temp.x][temp.y] = true;
Q.push(temp);
}
}
}
return -1;
}
void work() {
char c1, c2;
int a, b, ans;
while (scanf("%c%d %c%d", &c1, &a, &c2, &b) == 4) {
start.x = a - 1;
start.y = c1 - 'a';
endx = b - 1;
endy = c2 - 'a';
start.step = 0;
ans = BFS();
printf("To get from %c%d to %c%d takes %d", c1, a, c2, b, ans);
puts(" knight moves.");
getchar();
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
work();
return 0;
}