您的位置:首页 > 其它

POJ 3278 Catch That Cow --- 简单BFS

2015-12-19 02:00 495 查看
/* POJ 3278 Catch That Cow --- 简单BFS */
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

const int maxn = 100005;
bool visit[maxn];
int step[maxn];

int bfs(int n, int k){
if (n == k)
return 0;
memset(visit, 0, sizeof visit);
queue<int> q; //对中存储已访问但下一个点待判断的结点
q.push(n);
step
= 0;
visit
= 1;
int x,next;

while (!q.empty()){
x = q.front(); q.pop();

for (int i = 0; i < 3; ++i){
//i = 0,1,2表示分别按不同的方向广搜
if (i == 0)
next = x - 1;
else if (i == 1)
next = x + 1;
else
next = x * 2;

//是否越界和是否已访问的判断
if (visit[next] || next < 0 ||next >= maxn)
continue;
visit[next] = 1;
step[next] = step[x] + 1; //步数+1
if (next == k)
return step[next];
q.push(next);
}
//q.pop();
}
return -1;
}

int main()
{
int n, k;
while (scanf("%d%d", &n, &k) == 2){
printf("%d\n", bfs(n, k));
}

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: