广搜, 那个Knight是走"日"字的, 就像中古想起里面的马走法一样哦, 那么它在不出范围的情况下就有8个方向哦.
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct cell {
int x, y;
int step;
};
int dir[8][2] = {-2, -1, -2, 1, -1, 2, 1, 2, 2, 1, 2, -1, 1, -2, -1, -2}; // 8个方向哦
bool visited[9][9];
cell start, end, go, to;
int bfs() {
int i;
queue<cell> Q;
Q.push(start);
memset(visited, false, sizeof(visited));
visited[start.x][start.y] = true;
while (!Q.empty()) {
go = Q.front();
Q.pop();
for (i = 0; i < 8; i++) {
to.x = go.x + dir[i][0];
to.y = go.y + dir[i][1];
to.step = go.step;
if (to.x == end.x && to.y == end.y) {
return to.step + 1;
}
if (to.x >= 1 && to.x <= 8 && to.y >= 1 && to.y <= 8 && !visited[to.x][to.y]) {
++to.step;
visited[to.x][to.y] = true;
Q.push(to);
}
}
}
return 0;
}
int main() {
char s[3], e[3];
int ans;
while (scanf("%s %s", s, e) == 2) {
start.x = s[1] - '0';
start.y = s[0] - 'a' + 1;
start.step = 0;
end.x = e[1] - '0';
end.y = e[0] - 'a' + 1;
if (start.x == end.x && start.y == end.y) {
printf("To get from %s to %s takes 0 knight moves.\n", s, e);
continue ;
}
ans = bfs();
printf("To get from %s to %s takes %d knight moves.\n", s, e, ans);
}
return 0;
}