HDU1372 Knight Moves(BFS)

做的第一道BFS,和DFS差不多,是有差不多的模板的,基本上每道题的写法都差不多,有时间的话会在博客里写一些模板的东西

#include<iostream>
#include<string.h>
#include<queue>
using namespace std;

int dir[8][2] = {-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
int map[10][10],a,b;
char str1[2],str2[2];

struct node{
	int x,y,s;
};

int bfs(){
	queue<node> Q;
	node t,q,p;
	t.x = str1[0]-'a';
	t.y = str1[1]-'1';
	t.s = 0;
	memset(map,0,sizeof(map)); 
	map[t.x][t.y] = 1;
	Q.push(t);
	while(!Q.empty()){
		q = Q.front();
		Q.pop();
		if(q.x == (str2[0]-'a') && q.y == (str2[1]-'1'))
			return q.s;
		for(int i = 0;i<8;i++){
			p.x = q.x + dir[i][0];
			p.y = q.y + dir[i][1];
			if(p.x == (str2[0]-'a') && p.y == (str2[1]-'1'))
				return q.s+1;
			if(p.x>=0 && p.x<8 && p.y>=0 && p.y<8 && map[p.x][p.y] == 0){
				p.s = q.s+1;
				map[p.x][p.y] = 1;
				Q.push(p);
			}
		}
	}
}

int main(){
	while(~scanf("%s %s",&str1,&str2)){
		printf("To get from %s to %s takes %d knight moves.\n",str1,str2,bfs());
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值