广搜,由于要记录步数,所以又用到了滚动队列。
一开始没判断起点和终点在一起的情况,WA了一次
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
char ss[3], dd[3];
int map[9][9];
int dx, dy;
int point[8][2] = {{1, 2}, {1, -2}, {-1, -2}, {-1, 2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
int ans;
struct Node {
int xx, yy;
Node() {}
Node(int x, int y) {
xx = x;
yy = y;
}
};
queue<Node> que[2];
void bfs() {
Node tmp = que[0].front();
int a, b;
a = 0, b = 1;
int s1, s2;
s1 = tmp.xx;
s2 = tmp.yy;
memset(map, 0, sizeof(map));
map[s1][s2] = 1;
while(!que[a].empty()) {
swap(a, b);
ans++;
while(!que[b].empty()) {
tmp = que[b].front();
que[b].pop();
int a1, a2;
a1 = tmp.xx;
a2 = tmp.yy;
map[a1][a2] = 0;
for(int i = 0; i < 8; i++) {
int xx = a1 + point[i][0];
int yy = a2 + point[i][1];
if(xx == dx && yy == dy) {
return;
}
else if(xx >= 1 && xx <= 8 && yy >= 1 && yy <= 8) {
map[xx][yy] = 1;
que[a].push(Node(xx, yy));
}
}
}
}
}
int main() {
while(scanf("%s%s", ss, dd) != EOF) {
int sx, sy;
ans = 0;
sx = ss[0] - 'a' + 1;
sy = ss[1] - '0';
dx = dd[0] - 'a' + 1;
dy = dd[1] - '0';
if(sx == dx && sy == dy) {
printf("To get from %s to %s takes 0 knight moves.\n", ss, dd);
continue;
}
while(!que[0].empty()) que[0].pop();
while(!que[1].empty()) que[1].pop();
que[0].push(Node(sx, sy));
bfs();
printf("To get from %s to %s takes %d knight moves.\n", ss, dd, ans);
}
return 0;
}