码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1372 Knight Moves

时间:2015-04-23 19:11:15      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

最近在学习广搜  这道题同样是一道简单广搜题=0=

题意:(百度复制粘贴0.0)

题意:给出骑士的骑士位置和目标位置,计算骑士要走多少步

思路:首先要做这道题必须要理解国际象棋中骑士的走法,国际象棋中,骑士是在一个3*2的格子中进行对角线移动,通过画图很容易就知道骑士最多可以朝八个方向移动,那么就朝8个方向进行BFS即可

//细节注意:

1.输入开始结束坐标时需要保存  所以我用了全局变量  因为输出还需要他们=0=;

2.依旧是用bool类型进行map保存,防止内存超限, 0表示还未走过, 1表示走过此点;

3.结束标志  找到e_x, e_y 此点;

4.BFS开始之前直接把开始坐标s_x, s_y转化好, 开始点从a-h表示X下标0-7, 1-8表示y下标0-7;

 

代码奉上:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define N 60
using namespace std;

int dir[8][2] = {1,2, 2,1, -1,2, 2,-1, 1,-2, -2,1, -1,-2, -2,-1};
bool maps[10][10];
char ch1, ch2;//输入时时字符 分表表示s_x e_x
int s_x, s_y, e_x, e_y;//开始坐标与结束坐标

typedef struct xy
{
int x, y, step;
} zb;//step保存从开始到此坐标需走步数
zb s, e;

void BFS()
{
int x, y;
zb v;
queue<zb>q;

q.push(s);

while(!q.empty())
{
int i;
s = q.front();
if(s.x == e.x && s.y == e.y)
{
printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, s_y + 1, ch2, e_y + 1, s.step);
return;//输出时记得y下标比给的值大一 更正回来
}
q.pop();

for(i = 0; i < 8; i++)
{
x = s.x + dir[i][0];
y = s.y + dir[i][1];
if(x >= 0 && x < 8 && y >= 0 && y < 8 && maps[x][y] == 0)
{
maps[x][y] = 1;//走过标记
v = {x, y, s.step + 1};//步数别忘记加1
q.push(v);
}
}
}

}

int main()
{

while(~scanf(" %c%d %c%d", &ch1, &s_y, &ch2, &e_y))
{
memset(maps, 0, sizeof(maps));
s_x = ch1 - ‘a‘;
s_y--;//给的Y比下标大1
e_x = ch2 - ‘a‘;
e_y--;
s = {s_x, s_y, 0};
e = {e_x, e_y};
maps[s.x][s.y] = 1;//开始点记得标记已走过
BFS();
}
}

 

HDU 1372 Knight Moves

标签:

原文地址:http://www.cnblogs.com/wangyuhao/p/4451117.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!