您的位置:首页 > 其它

HDU 1372 Knight Moves【广搜】

2017-11-15 10:37 344 查看
题目链接

题目意思

类似于中国象棋中的马走日,就是给一个7*7的棋盘,现在给你两个点,让你计算从一个点到另一个点按照马走日的走法,需要走几步。

解题思路

就是一个简单的广搜,注意搜的方向是按照日字型来搜的,其他的和普通的广搜也没有区别。

代码部分

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
char a[10],b[10];
int maps[10][10];
int dir[8][2]={{2,1},{-2,1},{1,2},{1,-2},{2,-1},{-2,-1},{-1,2},{-1,-2}};
int sx,sy,ex,ey;
struct node
{
int x,y,num;
};
void bfs(int x,int y)
{
node p,q;
queue<node>Q;
p.x=x;
p.y=y;
p.num=0;
memset(maps,0,sizeof(maps));
maps[p.x][p.y]=1;
Q.push(p);
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(p.x==ex&&p.y==ey)
{
cout<<"To get from "<<a<<" to "<<b<<" takes "<<p.num<<" knight moves."<<endl;
return;
}
for(int i=0; i<8; i++)
{
q.x=p.x+dir[i][0];
q.y=p.y+dir[i][1];
if(q.x>=0&&q.y>=0&&q.x<8&&q.y<8&&!maps[q.x][q.y])
{
q.num=p.num+1;
maps[q.x][q.y]=1;
Q.push(q);
}
}
}
}
int main()
{
while(scanf("%s%s",a,b)!=EOF)
{
sx=a[0]-'a';
sy=a[1]-'1';
ex=b[0]-'a';
ey=b[1]-'1';
bfs(sx,sy);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: