您的位置:首页 > 其它

hoj 1440 - Knight Moves

2008-02-01 23:08 288 查看
http://acm.hit.edu.cn/ojs/show.php?Proid=1440&Contestid=0

这是我第一次写BFS的题,现在感觉还是很简单的。

初看此题是在N久之前,当时觉得无从下手,感觉可以用搜索解本题,想了一会
不知道怎么写,pass。最近做了poj 1088 - 滑雪,受到了些启发,稍加思索,终于

把这道题A掉了。

解题过程:

先做一些预处理,将起点和终点转化为相应的坐标

从起点开始进行BFS,直到跳到终点为止。具体做法是先建立一

个队列,把起点压进队。每次搜索时取队首元素,对于队首元素可跳到
的八个点,判断是否为终点,是则停止搜索,不是则把该点压进队;若
判断完这八个点后没跳到终点,则取队首重复上述方法继续搜索。
解题时需要注意几点:

从一点可以跳向周围的八个点,跳之前需要判断是否跳出界

建立一个标记数组检测一个点是否搜索过,如搜索过则不再搜索

附代码

#include <iostream>
#include <cmath>
#include <algorithm>
#include <functional>
#include <vector>
#include <queue>

using namespace std;
struct point
{
int x, y, step;
}
p, a, b, temp;
int dic[8][2] = {{-1, -2}, {-1, 2}, {1, 2}, {1, -2}, {-2, -1}, {-2, 1}, {2, 1}, {2, -1}};
int find();
bool flag[8][8];
int main()
{
char start[3], end[3];

while (scanf("%s%s", start, end) != EOF)
{
a.x = start[0] - 'a';
a.y = start[1] - '1';
b.x = end[0] - 'a';
b.y = end[1] - '1';
memset(flag, 0, sizeof(flag));

printf("To get from %s to %s takes %d knight moves./n", start, end, find());

}

return 0;
}
int find()
{
int ans = 0, i;
bool mark = true;
queue <point> q;

if (a.x == b.x && a.y == b.y)
{
mark = false;
}
else
{
a.step = 0;
q.empty();
q.push(a);
flag[a.x][a.y] = true;
}

while (mark)
{
p = q.front();
q.pop();
for (i = 0; i < 8; i++)
{
temp.x = p.x + dic[i][0];
temp.y = p.y + dic[i][1];
if (temp.x == b.x && temp.y == b.y)
{
ans = p.step + 1;
mark = false;
break;
}
else if (temp.x >= 0 && temp.x < 8 && temp.y >= 0 && temp.y < 8 && flag[temp.x][temp.y] == false)
{
flag[temp.x][temp.y] = true;
temp.step = p.step + 1;
q.push(temp);
}
}
}

return ans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: