题目描述
你的一位朋友正在研究骑士旅行问题(TKP)。在一个有n个方格的棋盘上,你得找到一条最短的封闭骑士旅行的路径,使其能遍历每个方格一次。他认为问题的最困难部分在于,对两个给定的方格,确定骑士移动所需的最小步数。你曾经解决过这类问题,找到这个路径应该不困难。
当然,你知道反之亦然,所以你帮助他编写一个程序,解决这个“困难的”部分。
P.S. 骑士指的是马.
输入格式
输入包含一组或多组测试例。每个测试例一行,是两个方格,用空格隔开。棋盘上的一个方格用一个字符串表示,字母(a-h)表示列,数字(1-8)表示行。
输出格式
对每个测试例,输出一行:“To get from xx to yy takes n knight moves.”。
样例输入
e2 e4
a1 b2
b2 c3
样例输出
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.
提示
对于样例的解释:
e2->c3->e4
a1->c2->b4->d3->b2
b2->d1->c3
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxx = 1000050;
int n, m, k, t, now, p;
const double pi = acos(-1.0);
int step[220][220];
int ex, ey, sx, sy;
int dx[] = { 1, 1, -1, -1, 2, 2, -2, -2 };
int dy[] = { 2, -2, 2, -2 , 1, -1 , 1 , -1 };
struct node
{
int x, y;
node(int xx = 0, int yy = 0)
{
x = xx;
y = yy;
}
};
void bfs()
{
memset(step, 0x3f, sizeof(step));
queue<node> q;
q.push(node(sx, sy));//将其推入队列
step[sx][sy] = 0;//初始步数为0;
while (!q.empty())//不为空
{
node f = q.front();//将队首取出
q.pop();//将其删除即可//因为即将将其遍历完
if (f.x == ex && f.y == ey)//
{
return;
}
for (int i = 0; i < 8; i++)//将所有方向都遍历
{
int nx = f.x + dx[i];
int ny = f.y + dy[i];
if (nx >= 1 && nx <= 8 && ny >= 1 && ny <= 8)
{
if (step[nx][ny] == 0x3f3f3f3f)//当其并未走过时就继续
{
q.push(node(nx, ny));//将其继续推入队列
step[nx][ny] = step[f.x][f.y] + 1;//步数++
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string x, y;
while (cin >> x >> y)
{
sx = x[0] - 'a' + 1;
sy = x[1] - '0';
ex = y[0] - 'a' + 1;
ey = y[1] - '0';//数据预处理
bfs();
cout << "To get from " << x << " to " << y << " takes " << step[ex][ey] << " knight moves." << endl;
}
return 0;
}