hdu 1372 Knight Moves(BFS)

本文介绍了一个基于广度优先搜索(BFS)算法的程序,该程序用于计算在中国象棋棋盘上,从一个指定位置到另一个指定位置所需的马走法的最少步数。通过使用8个方向的移动规则,程序能够有效地找到最优路径。

原题链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1372


题目大意:

横坐标为a~h

纵坐标为1~8

求从A位置到B位置所走的最少步数。

走的方式为中国象棋中马的八种方式。


代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN=9;
int G[MAXN][MAXN];
bool flog[MAXN][MAXN];//标记
const int nextr[]={-2,-2,-1,+1,+2,+2,+1,-1};//8个方向
const int nextc[]={-1,+1,+2,+2,+1,-1,-2,-2};
const char base='a'-1;
int c1,c2;
char r1,r2;
struct g
{
	int r,c;
	int step;
};
bool check(int r,int c)//判断能否走到下一步
{
	if(r<1||r>8||c<1||c>8||flog[r][c])
		return false;
	return true;
}
int BFS()
{
	queue<g>q;
	g pos;
	pos.r=r1-base;
	pos.c=c1;
	pos.step=0;
	flog[pos.r][pos.c]=true;
	q.push(pos);
	while(!q.empty())
	{
		pos=q.front();
		q.pop();
		if(pos.r==r2-base&&pos.c==c2) return pos.step;
		for(int i=0;i<8;i++)
		{
			g temp;
			temp.r=pos.r+nextr[i];
			temp.c=pos.c+nextc[i];
			temp.step=pos.step+1;
			if(check(temp.r,temp.c))
				q.push(temp);
		}
	}

}
int main()
{

	while(scanf("%c%d%*c%c%d",&r1,&c1,&r2,&c2)!=EOF)
	{
		//cout<<r1<<c1<<r2<<c2<<endl;
		memset(flog,0,sizeof(flog));
		printf("To get from %c%d to %c%d takes %d knight moves.\n",r1,c1,r2,c2,BFS());
		getchar();
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值