蓝桥杯备考:BFS之Catch That Cow S
这道题一样,我们可以用BFS层序遍历的方式来做
我们的剪枝策略就是如果走到已经标记过的数,就跳过,因为这条路一定不是最短的
#include <iostream>
#include <cstring>
#include <queue>
const int N = 1e5 + 10;
using namespace std;
int t;
int dist[N];
int x, y;
void bfs()
{
queue<int>q;
q.push(x);
dist[x] = 0;
while (q.size())
{
int t = q.front(); q.pop();
int a = t + 1;
int b = t - 1;
int c = t * 2;
if (a <= N && dist[a] == -1)
{
dist[a] = dist[t] + 1;
q.push(a);
}
if (b >= 0 && dist[b] == -1)
{
dist[b] = dist[t] + 1;
q.push(b);
}
if (c <= N && dist[c] == -1)
{
dist[c] = dist[t] + 1;
q.push(c);
}
if (a == y || b == y || c == y)
{
return;
}
}
}
int main()
{
cin >> t;
while (t--)
{
memset(dist, -1, sizeof(dist));
cin >> x >> y;
bfs();
cout << dist[y] << endl;
}
return 0;
}