国际象棋里面的骑士和中国象棋里面的马走法是相同的,走日字。所以如果以一个点为中心的话,可以向外扩散八个方向(也就是说可以走出八种方向不同的日字)。所以只用常规BFS+八个方向的搜索就好辣。
代码如下:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long LL;
using namespace std;
int m[10][10];
int re[10][10];
int dr[8][2] = {{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
struct knight
{
int x, y, step;
knight(int x1, int y1, int step1):x(x1), y(y1), step(step1){
}
};
int bfs(int x, int y, int end_x, int end_y)
{
queue<knight> q;
knight s(x, y, 0);
while (!q.empty())
q.pop();
q.push(s);
while (!q.empty())
{
knight temp = q.front();
q.pop();
if (temp.x == end_x && temp.y == end_y)
{
return temp.step;
}
for (int i=0; i<8; i++)
{
int t1 = temp.x + dr[i][0];
int t2 = temp.y + dr[i][1];
if (t1>=1 && t1 <=8 && t2 >=1 && t2 <= 8 && !re[t1][t2])
{
re[t1][t2] = 1;
knight test(t1, t2, temp.step+1);
q.push(test);
}
}
}
}
int main()
{
char a[3], b[3];
while (scanf("%s", a) != EOF)
{
getchar();
scanf("%s", b);
memset(re, 0, sizeof(re));
m[a[1]-48][a[0]-96] = 1;
m[b[1]-48][b[0]-96] = 1;
re[a[1]-48][a[0]-96] = 1;
cout << "To get from " << a << " to " << b << " takes " << bfs(a[1]-48, a[0]-96, b[1]-48, b[0]-96) << " knight moves." << endl;
}
}