题目大意:国际象棋骑士从起点到终点的最少步数
解题思路:水题.....宽度遍历
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;
struct node
{
int x, y, step;
};
const int maxn = 8;
bool square[maxn][maxn];
int sx, sy, ex, ey;
int dir[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
int bfs();
int main()
{
char str1[5], str2[5];
while(scanf("%s %s", str1, str2) != EOF)
{
sx = str1[1] - '1'; sy = str1[0] - 'a';
ex = str2[1] - '1'; ey = str2[0] - 'a';
memset(square, 0, sizeof(square));
int ans = bfs();
printf("To get from %s to %s takes %d knight moves.\n", str1, str2, ans);
}
return 0;
}
int bfs()
{
queue<node> que;
node tmp, t;
t.x = sx;
t.y = sy;
t.step = 0;
square[t.x][t.y] = true;
que.push(t);
while(!que.empty())
{
tmp = que.front();
if(tmp.x == ex && tmp.y == ey)
return tmp.step;
que.pop();
for(int i = 0; i < 8; i++)
{
t.x = tmp.x + dir[i][0];
t.y = tmp.y + dir[i][1];
t.step = tmp.step + 1;
if(t.x >= 0 && t.x < 8 && t.y >= 0 && t.y < 8 && !square[t.x][t.y])
{
square[t.x][t.y] = true;
que.push(t);
}
}
}
return -1;
}