您的位置:首页 > 其它

UVA 439 Knight Moves (BFS)

2016-05-12 21:02 519 查看
题意:给国际象棋棋盘的两个坐标,求某个棋子(我也看不懂,规则跟中国象棋里的马一样的)从初始坐标到末坐标的步数,计算最少步数到达目标点并输出,思路就是bfs搜索即可

代码如下

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#include<set>
#include<cctype>
#include<istream>
#include<ostream>
#include<list>
#define INF 0x3f3f3f3f
#define mem(x) memset(x,0,sizeof(x))
#define rep(n) for(int i=1;i<=n;i++)
#define rep1(n) for(int j=1;j<=n;j++)
const double EPS=1e-6;
const double PI=acos(-1.0);
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
typedef pair<int,int> p;
char c1,c2;
int r1,r2,sx,sy,ex,ey;
int ans;
int d[10][10];
int dx[8]= {2,2,-2,-2,1,-1,1,-1};
int dy[8]= {1,-1,1,-1,2,2,-2,-2};
void bfs()
{
rep(8)
rep1(8)
d[i][j]=INF;
d[sx][sy]=0;
queue<p> q;
q.push(p(sx,sy));
while(q.size())
{
p pp=q.front();
q.pop();
int x=pp.first,y=pp.second;
if(x==ex&&y==ey) {ans=d[ex][ey];break;}
if(d[x][y]==INF) continue;
for(int i=0; i<8; i++)
{
int xx=x+dx[i],yy=y+dy[i];
if(d[xx][yy]==INF&&xx>=1&&xx<=8&&yy>=1&&yy<=8) d[xx][yy]=d[x][y]+1;
else continue;
q.push(p(xx,yy));
}
}
}
int main()
{
while(cin>>c1>>r1>>c2>>r2)
{
ans=0;
sx=c1-'a'+1;sy=r1;
ex=c2-'a'+1;ey=r2;
bfs();
printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,r1,c2,r2,ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs uva