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\n", bfs(n, k));
    }

    return 0;
}
View Code

 

posted @ 2015-12-19 02:00  tan90丶  阅读(130)  评论(0编辑  收藏  举报