HDU 1372 - Knight Moves

(感觉自己越来越懒了,题目都不用贴了……)

谨以此纪念一下自己学会的第一道BFS~

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct type{
	int x,y,step;
}st,ed;
bool s[10][10];
int dir[8][2] = {{-1,+2},{-2,+1},{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2}};

int bfs()
{
	queue<type> q;
	memset(s,0,sizeof(s));
	s[st.x][st.y]=1;
	q.push(st);
	while(!q.empty())
	{
		type next,now=q.front();q.pop();
		//printf("now: x=%d y=%d step=%d\n",now.x,now.y,now.step);
		if(now.x == ed.x && now.y == ed.y) return now.step;
		for(int i=0;i<8;i++)
		{
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			next.step=now.step+1;
			if(next.x>=1 && next.y>=1 && next.x<=8 && next.y<=8 && s[next.x][next.y]==0)
			{
				s[next.x][next.y]=1;
				q.push(next);
			}
		}
	}
}

int main()
{
	char begin[2],end[2];
	while(scanf("%c%c %c%c%*c",&begin[0],&begin[1],&end[0],&end[1])!=EOF)
	{
		st.x=begin[1]-'0';
		st.y=begin[0]-'a'+1;
		st.step=0;
		//printf("st: x=%d y=%d\n",st.x,st.y);
		ed.x=end[1]-'0';
		ed.y=end[0]-'a'+1;
		//printf("ed: x=%d y=%d\n",ed.x,ed.y);
		int ans=bfs();
		printf("To get from %c%c to %c%c takes %d knight moves.\n",begin[0],begin[1],end[0],end[1],ans);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值