C

  这是我第一次遇到的BFS问题,因为要学习编程,F同学帮我找了一些搜索的题目,做到这个问题的时候感觉无法使用DFS来写,因为他可能是个无底洞。因为当时没有学习过BFS,所以网上搜索了下发现了也是一位第一次碰到BFS题目就是C - Catch That Cow的博主,学习了他的代码,他的代码解释很清楚。

  感谢博主,传送门http://blog.csdn.net/weiwanshu/article/details/45770537

  题目的意思是农民的牛丢了,农民不知道牛在哪里,只能一点一点的去寻找,已知的是农民和牛在一条直线上,农民需要找到他的牛。农民有两种行走方法,一种是走,一分钟可以前进1个单位也可以后退1个单位,第二种方法是跳跃,每次只能向前跳,跳的位置是当前位置的2倍。给出农民和牛的位置求出最快多久找到牛。

样例

Sample Input
5 17
Sample Output
4

代码

#include<stdio.h>
#include<string.h>
struct A {
    int state;
    int step;
}queue[100001];
int n,k;
int bfs(int start);
int book[100001];
int main(){
    scanf("%d%d",&n,&k);
    memset(book,0,sizeof(book));
    if(n>=k) printf("%d",n-k);
    else printf("%d",bfs(n));
}
int bfs(int start){
    struct A temp;
    int head=0;
    int rear=0;
    queue[head].state=start;
    queue[rear++].step=0;
    book[start]=1; 
    while(head<rear){
        temp=queue[head++];
        if(temp.state+1>0&&temp.state+1<100001&&book[temp.state+1]==0){
            queue[rear].state=temp.state+1;
            queue[rear++].step=temp.step+1;
            book[temp.state+1]=1;
            if(temp.state+1==k)
                return temp.step+1;         
        } 
        if(temp.state-1>0&&temp.state-1<100001&&book[temp.state-1]==0){
            queue[rear].state=temp.state-1;
            queue[rear++].step=temp.step+1;
            book[temp.state-1]=1;
            if(temp.state-1==k)
                return temp.step+1;         
        } 
        if(temp.state*2>0&&temp.state*2<100001&&book[temp.state*2]==0){
            queue[rear].state=temp.state*2;
            queue[rear++].step=temp.step+1;
            book[temp.state*2]=1;
            if(temp.state*2==k)
                return temp.step+1;         
        } 
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lvcoding/p/6557453.html