#include <stdio.h>
#include <queue>
#include <cstring>#define N 100001
using namespace std;bool mark[N]; //标记是否遍历
int go[3] = {1, -1, 2}; //方向数组struct E
{
int x, t;
};queue<E> q; //用队列来存储符合条件的可以被扩展的状态
int BFS(int a, int b)
{
while(q.empty() == false)
{
E t = q.front();
q.pop();
if(a == b)
return 0;
//从当前位置,向3个方向扩展,将符合条件的点入队列
int nx;
for(int i = 0; i < 3; i++)
{
if(i == 2)
nx = t.x * go[i];
else
nx = t.x + go[i];
if(nx < 0 || nx >= N)
continue;
if(mark[nx] == true)
continue;
E tmp;
tmp.x = nx;
tmp.t = t.t + 1;
mark[tmp.x] = true;
q.push(tmp);
if(tmp.x == b)
return tmp.t;
}
}
}int main()
{
int n, m;
while(scanf("%d%d", &n, &m) != EOF)
{
//初始化
memset(mark, 0, sizeof(mark));
while(q.empty() == false)
q.pop();
E start;
start.x = n;
start.t = 0;
mark[start.x] = true;
q.push(start);
int ans = BFS(n, m);
printf("%d\n", ans);
}
return 0;
}
HDU-2717-Catch that Cow (BFS)
最新推荐文章于 2021-01-30 15:38:45 发布