国际象棋中,骑士在一个 3*2 的格子中进行对角线移动,即可以朝八个方向移动,依次进行广搜即可。
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int dx[8] = { -2,-2,-1,-1,1,1,2,2 };
int dy[8] = { 1,-1,2,-2,2,-2,1,-1 };
bool vis[25][25];
struct node //棋盘上的格子
{
int x, y; //坐标
int step; //移动步数
};
//广搜,搜索从(sx,sy)到(ex,ey)的最小步数
int BFS(int sx, int sy, int ex, int ey)
{
node start;
start.x = sx; start.y = sy; start.step = 0;
queue<node> q;
q.push(start);
node now, next;
while (!q.empty())
{
now = q.front();
q.pop();
if (now.x == ex && now.y == ey) //到达终点
return now.step;
for (int i = 0; i < 8; i++) //依次搜索8个位置
{
next.x = now.x + dx[i];
next.y = now.y + dy[i];
next.step = now.step + 1;
if (!vis[next.x][next.y] && next.x > 0 && next.y > 0 && next.x <= 8 && next.y <= 8)
{
vis[next.x][next.y] = 1;
q.push(next);
}
}
}
}
int main()
{
char s1[2], s2[2];
while (cin >> s1 >> s2)
{
memset(vis, 0, sizeof(vis));
int x1 = s1[0] - 'a' + 1;
int y1 = s1[1] - '0';
int x2 = s2[0] - 'a' + 1;
int y2 = s2[1] - '0';
cout << "To get from " << s1 << " to " << s2 << " takes " << BFS(x1, y1, x2, y2) << " knight moves." << endl;
}
}
继续加油。