首页 > 其他 > 详细

POJ 3278 Catch That Cow --- 简单BFS

时间:2015-12-19 06:31:38      阅读:213      评论:0      收藏:0      [点我收藏+]

 

技术分享
/* 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[n] = 0;
    visit[n] = 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

 

POJ 3278 Catch That Cow --- 简单BFS

原文:http://www.cnblogs.com/tommychok/p/5058563.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!