C - Catch That Cow


  這是我第一次遇到的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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM