hdu 1372 Knight Moves

本文介绍了 HDU 1372 KnightMoves 的解题思路及 BFS 实现方法,该题要求计算骑士从一个位置移动到另一个位置所需的最少步数。

hdu   1372   Knight Moves              题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372

                                                             

题目大意:同样还是跑马数步数(不过千万别以为是和poj1915一样的题啊~)

题目分析:存下起止坐标之后,剩下的就跟poj1915的BFS完全一样了。

code:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int n=8,dir[8][2]={1,2,-1,2,2,1,2,-1,1,-2,-2,-1,-1,-2,-2,1};
char g[10][10];
struct node
{
	int x,y,step;
};
bool judge(int x,int y)
{
	return x<n&&y<n&&x>=0&&y>=0&&g[x][y]==0;
}
int bfs(int x,int y,int ex,int ey)
{
	queue<node>q;
	node first,next;
	first.x=x,first.y=y,first.step=0;
	q.push(first);
	while(!q.empty())
	{
		first=q.front();
		if(first.x==ex&&first.y==ey)return first.step;
		q.pop();
		g[first.x][first.y]=1;
		for(int i=0;i<8;i++)
		{
			next.x=first.x+dir[i][0];
			next.y=first.y+dir[i][1];
			if(judge(next.x,next.y))
			{
				next.step=first.step+1;
				q.push(next);
				if(next.x==ex&&next.y==ey)return next.step;
				g[next.x][next.y]=1;
			}
		}
	}
	return -1;
}
int main()
{
	int i,j,t,sx,sy,ex,ey,ans;
	char s[8];
	while(gets(s))
	{
		memset(g,0,sizeof(g));
		sx=s[0]-'a',sy=s[1]-'1',ex=s[3]-'a',ey=s[4]-'1';
		ans=bfs(sx,sy,ex,ey);
		printf("To get from %c%c to %c%c takes %d knight moves.\n",s[0],s[1],s[3],s[4],ans);
	}
	return 0;
}

PS:做完poj1915直接转到这道题,想也没想就把代码粘过来了,果断runtime error……







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值