这是一道经典的BFS,比较简单~
#include <queue>
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 20;
int vis[maxn][maxn];
int dir[][2] = {{2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}};
struct Node {
int x;
int y;
int step;
Node(int tx, int ty, int tstep) {
x = tx;
y = ty;
step = tstep;
}
};
Node walk(const Node & n, int i) {
return Node(n.x + dir[i][0], n.y + dir[i][1], n.step + 1);
}
Node ToNode(char* p) {
return Node(p[0] - 'a' + 1, p[1] - '0', 0);
}
bool inside(Node t) {
return (t.x <= 8 && t.x >= 1 && t.y <= 8 && t.y >= 1);
}
int main() {
//freopen("input.txt", "r", stdin);
char b[3], e[3];
while(scanf("%s%s", b, e) != -1) {
memset(vis, 0, sizeof(vis));
Node start = ToNode(b);
Node en = ToNode(e);
queue<Node> qu;
qu.push(start);
while(!qu.empty()) {
Node v = qu.front();
if (v.x == en.x && v.y == en.y) {
printf("To get from %s to %s takes %d knight moves.\n", b, e, v.step);
break;
}
qu.pop();
vis[v.x][v.y] = 1;
for(int i = 0; i < 8; i++) {
Node n = walk(v, i);
if (!inside(n)) continue;
if (!vis[n.x][n.y]) {
qu.push(n);
}
}
}
}
return 0;
}