poj 3728 catch the cow (bfs)广搜

     农夫抓牛的问题,农夫的行进方式是:+1;-1;*2.求农夫抓到牛的最小步数。是基础的广搜题。

代码如下:

#include<iostream>
#include<queue>
using namespace std;
const int Max=100050;

int main()
{ 
	queue<int> a;
	bool visit[Max];
	int n,k;
	cin>>n>>k;
	memset(visit,false,sizeof(visit));
	bool fine=false;
	int steps=0;
	visit[n]=true;
	a.push(n);//将农夫的位置放入队列中
	if(n!=k)
	{

		while(!a.empty()&&!fine)
		{
			int t=a.size();
			steps++;
			while(t--)
			{
				int pos,npos[3];//进行三种移动方法
				pos=a.front();
				a.pop();           //删除首元素
				npos[0]=pos+1;
				npos[1]=pos-1;
				npos[2]=pos*2;
				for(int i=0;i<3;i++)
				{
					if(npos[i]==k)
					{
						fine=true;
						break;
					}
					if(npos[i]>=0 && npos[1]<=100000 && !visit[npos[i]])//没有越界并且没有被访问过
					{
						visit[npos[i]]=true;
						a.push(npos[i]);      //往队列中压入元素
					}
				}
			}
		}
	}
	cout<<steps<<endl;
	return 0;
}






发布了40 篇原创文章 · 获赞 7 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章