zoukankan      html  css  js  c++  java
  • POJ 3278 Catch That Cow --- 简单BFS

    /* 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
    ", bfs(n, k));
        }
    
        return 0;
    }
    View Code
  • 相关阅读:
    std::function与std::bind 函数指针
    cocos2dx 3.0 +VS2013 环境搭建
    matrix(dp)
    sequence1(暴力)
    uva
    hpu第五届acm比赛
    找球号(一)(hask表)
    Elven Postman(二叉树)
    链表的基本操作
    Sightseeing Cows(最优比率环)
  • 原文地址:https://www.cnblogs.com/tommychok/p/5058563.html
Copyright © 2011-2022 走看看