zoj 1091 (bfs搜索)

链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=91

 

结题报告:因该说10多天没有A题了,今天过了一道比较水的题目,也算是来纪念一下吧,最近在刷搜索的时候感觉bfs有些题目是比较难的,象蛇和梯子那道题整整卡了我一个星期但是现在仍然没有过,标记一下,有时间在回来看一下!

这道题注意两个地方,一个是下标的值,一个是vis数组标记!

 

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int dir[8][2] = {-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};
int mp[9][9];
int vis[9][9];
struct node 
{
	int x,y;
	int step;
};
queue<node>Q;
int ex,ey,sx,sy; 
int bfs(node p)
{
	node now,next;
	Q.push(p);
	while(!Q.empty())
	{
		now=Q.front();
		Q.pop();
		for(int i=0;i<8;i++)
		{
			int xx = now.x+dir[i][0];
			int yy = now.y+dir[i][1];
			if(xx<1||xx>8||yy<1||yy>8) continue;
			if(xx == ex && yy == ey) 
			{
				return now.step + 1;
			}
			if(!vis[xx][yy])
			{
				next.x=xx;
				next.y=yy;
				next.step = now.step+1;
				Q.push(next);
			}
			
		}
	}
	
}

int main( )
{
	char str1[5],str2[5];
	while(scanf("%s%s",str1,str2)!=EOF)
	{
		while(!Q.empty()) Q.pop();
		sx=str1[0]-'a'+1; sy=str1[1]-'0';
		ex=str2[0]-'a'+1; ey=str2[1]-'0';
		if(sx==ex&&sy==ey)
		{
			printf("To get from %s to %s takes 0 knight moves.\n",str1,str2);
			continue;
		}
		memset(vis,0,sizeof(vis));
		vis[sx][sy]=1;
		node p;
		p.x = sx; p.y = sy; p.step = 0;
		printf("To get from %s to %s takes %d knight moves.\n",str1,str2,bfs(p));
	}
	 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值