题意翻译
输入 8 × 8 的国际象棋棋盘上的 2 个格子(列:a ~ h,行:1 ~ 8),
求马至少多少步从起点(键盘输入的第一个位置)跳到终点(键盘输入的第二个位置)。
输入样例
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
输出样例
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
题解
BFS:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#define x first
#define y second
using namespace std;
const int N = 10;
typedef pair<int, int> PII;
int dist[N][N];
char a, b, c, d;
int x1, y1, x2, y2;
int dx[8] = {1, 1, -1, -1, 2, 2, -2, -2};
int dy[8] = {2, -2, 2, -2, 1, -1, 1, -1};
int bfs()
{
queue<PII> q;
q.push(make_pair(x1, y1));
dist[x1][y1] = 0;
while(q.size())
{
PII t = q.front();
q.pop();
if(t.x == x2 && t.y == y2) return dist[x2][y2];
for (int i = 0; i < 8; i ++)
{
int a = t.x + dx[i], b = t.y + dy[i];
if(a < 1 || a > 8 || b < 1 || b > 8) continue;
if(dist[a][b] != -1) continue;
q.push(make_pair(a, b));
dist[a][b] = dist[t.x][t.y] + 1;
}
}
}
int main()
{
while(cin >> a >> b >> c >> d)
{
memset(dist, -1, sizeof dist);
x1 = b - '0', y1 = a - 96, x2 = d - '0', y2 = c - 96;
printf("To get from %c%c to %c%c takes %d knight moves.\n", a, b, c, d, bfs());
}
return 0;
}
ps:这道题在洛谷提交有点麻烦,但是有一道类似的 【Knight Moves】