又一次做到这一题了, 记得第一次做的时候, 理解成DFS。(其实当时没有DFS || BFS的概念), 这一次做这题信手捏来。
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define DIRECTION_N 8
#define MAP_SIZE 8
#define REACHED 1
#define UNREACHED 0
struct Node {
int x, y;
int steps;
};
const int direction[DIRECTION_N][2] = {{1,2}, {-1,2}, {1,-2}, {-1,-2}, {2,1}, {-2,1}, {2,-1}, {-2,-1}};
int map[MAP_SIZE][MAP_SIZE];
Node end;
int BFS(Node);
bool ok(Node);
int main()
{
Node star;
char x1, x2, y1, y2;
while (scanf("%c%c %c%c%*c", &x1, &y1, &x2, &y2) != EOF) {
memset(map, UNREACHED, sizeof(map)); //全地图标记未到达
star.x = (int)(x1 - 'a');
star.y = (int)(y1 - '1');
star.steps = 0;
end.x = (int)(x2 - 'a');
end.y = (int)(y2 - '1');
printf("To get from %c%c to %c%c takes %d knight moves.\n", x1, y1, x2, y2, BFS(star));
}
return 0;
}
//广搜索
int BFS(Node star)
{
queue<Node> que;
que.push(star);
while (!que.empty()) {
Node root = que.front();
que.pop();
if (root.x == end.x && root.y == end.y) { //出口
return root.steps;
}
for (int i = 0; i < DIRECTION_N; i++) {
Node child = root;
child.x += direction[i][0];
child.y += direction[i][1];
child.steps++;
if (ok(child)) {
map[child.x][child.y] = REACHED;
que.push(child);
}
}
}
printf("no way\n");
return 0;
}
//判断行走是否合法
bool ok(Node now)
{
if (now.x >= 0 && now.x < MAP_SIZE && now.y >= 0 && now.y < MAP_SIZE && map[now.x][now.y] == UNREACHED) {
return true;
}
return false;
}