HDU 3278 Catch That Cow(简单bfs)

#include<iostream>
#include<queue>
using namespace std;
#define M 100001
#define INF 10000000
struct POINT
{
	int pos;
	int step;
} now, next;

int n, k;
queue<POINT>Q;
bool visited[M];
int main()
{
	int bfs();
	while (cin >> n >> k)
	{
		memset(visited, false, sizeof(visited));
		if (n < k)    cout << bfs() << endl;
		if (n == k)  cout << 0 << endl;
		if (n > k)    cout << n - k << endl;
	}
	return 0;
}


int bfs()
{
	while (!Q.empty())
		Q.pop();
	now.pos = n;
	now.step = 0;
	visited[now.pos] = true;
	Q.push(now);
	while (!Q.empty())//队列非空
	{
		now = Q.front();
		Q.pop();//队列首元素出站
		next = now;
		for (int i = 0; i < 3; i++)
		{
			if (i == 0)	//前进1步		     	
				next.pos = now.pos + 1;
			if (i == 1)	//后退1步	
				next.pos = now.pos - 1;
			if (i == 2)	//前进2倍		       	  
				next.pos = now.pos * 2;

			next.step = now.step + 1;//总步数

			if (next.pos == k) //抓住了
				return next.step;//返回步数
			if (next.pos < 0 || next.pos > M)
				continue;//越界  跳出
			if (!visited[next.pos])//未访问这个状态
			{
				visited[next.pos] = true;//标记
				Q.push(next);//入队列
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值