您的位置:首页 > 其它

Knight Moves UVA - 439(BFS典例)

2017-04-13 10:07 465 查看
给出国际象棋棋盘中的两个点,求马从一个点跳到另一个点的最少步数。

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int x, y;
char cx, cy;
const int maxn = 10;
int d[maxn][maxn];
int dc[] = { 1,2,2,1,-1,-2,-2,-1 };
int dr[] = { -2,-1,1,2,2,1,-1,-2 };
struct Node
{
int x, y;
Node(int x = 0, int y = 0) :x(x), y(y) {}
};
Node p[maxn][maxn];
bool in(int x, int y)
{
return x >= 1 && x <= 8 && y >= 1 && y <= 8;
}
void BFS()
{
queue<Node> Q;
Node u(x, cx - 'a' + 1);
Q.push(u);
memset(d, -1, sizeof(d));  //注意初始化顺序,此句与下一句不可颠倒
d[x][cx - 'a' + 1] = 0;

while (!Q.empty())
{
Node u = Q.front();
Q.pop();
if (u.x == y && u.y == (cy - 'a' + 1))
return;
for (int i = 0; i < 8; ++i)
{
Node v(u.x + dr[i], u.y + dc[i]);
if (in(v.x, v.y) && d[v.x][v.y] < 0)
{
d[v.x][v.y] = d[u.x][u.y] + 1;
p[v.x][v.y] = u;
Q.push(v);
}
}
}
}
int main()
{
while (cin>>cx>>x>>cy>>y)
{
BFS();
cout << "To get from " << cx << x << " to " << cy << y << " takes " << d[y][cy - 'a' + 1] << " knight moves." << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: