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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章