您的位置:首页 > 其它

bfs简单题----Knight Moves(hdu 1372)

2016-09-12 19:41 369 查看
题目大意:骑士移动,以象棋中的“马走日”移动的方式一样。给你一个方阵,以字母a~h代表列,以数字1~8代表行。

输入两个字符串,一个代表起点,一个代表终点,求在方阵范围里从起点到终点至少要走多少步。#include <iostream>
#include <string>
#include <queue>
using namespace std;
int s1,s2,e1,e2;
string a,b;
int mark[10][10];
int rule[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
struct node
{
int x,y,step;
};
int bfs()
{
queue<node> que;
node pre,next;
pre.x=s1;
pre.y=s2;
pre.step=0;
mark[pre.x][pre.y]=1;
que.push(pre);
while(!que.empty())
{
pre=que.front();
que.pop();
if(pre.x==e1&&pre.y==e2) {return pre.step; break;}
for(int i=0;i<8;i++)
{
next=pre;
if(next.x+rule[i][0]>0&&next.x+rule[i][0]<9
&&next.y+rule[i][1]>0&&next.y+rule[i][1]<9&&mark[next.x+rule[i][0]][next.y+rule[i][1]]==0 )
{
next.x+=rule[i][0];
next.y+=rule[i][1];
next.step++;
mark[next.x][next.y]=1;
que.push(next);
}
}
}
return 0;
}
int main()
{
while(cin>>a>>b)
{
s1=a[0]-'a'+1;
s2=a[1]-'0';
e1=b[0]-'a'+1;
e2=b[1]-'0';
memset(mark,0,sizeof(mark));
cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: