Catch That Cow

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

struct node {
	int x;
	int step;
};

int n, k, vis[100010];
node s, e;

int bfs()
{
	queue<node> q;
	node t, p;
	s.x = n;
	s.step = 0;
	vis[s.x] = 1;
	q.push(s);
	while(!q.empty())
	{
		t = q.front();
		q.pop();
		
		if(t.x == e.x)	return t.step;
		if(t.x < 0 || t.x > 100000)
			continue;
		
		// 向右走一步 
		if(t.x + 1 <= 100000 && vis[t.x + 1] == 0)
		{
			p.x = t.x + 1;
			p.step = t.step + 1;
			vis[p.x] = 1;
			q.push(p);
		}
		
		// 向左走一步 
		if(t.x - 1 >= 0 && vis[t.x - 1] == 0)
		{
			p.x = t.x - 1;
			p.step = t.step + 1;
			vis[p.x] = 1;
			q.push(p);
		}
		
		// 向右走两倍步数 
		if(t.x * 2 <= 100000 && vis[t.x * 2] == 0)
		{
			p.x = t.x * 2;
			p.step = t.step + 1;
			vis[p.x] = 1;
			q.push(p);
		}
	}
	return 0;
}

int main()
{
	int result;
	while(cin >> n >> k)
	{
		memset(vis, 0, sizeof(vis));
		s.x = n, e.x = k;
		result = bfs();
		cout << result << endl;
	}
	return 0;
} 

  

原文地址:https://www.cnblogs.com/mjn1/p/11630994.html