POJ 3287 (基礎BFS) Catch That Cow

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   2014   art   

這是做的第一道BFS,很基礎很簡單的題目

廣度優先搜尋演算法如下:(用QUEUE)
(1) 把初始節點S0放入Open表中;
(2) 如果Open表為空白,則問題無解,失敗
退出;
(3) 把Open表的第一個節點取出放入
Closed表,並記該節點為n;
(4) 考察節點n是否為目標節點。若是,
則得到問題的解,成功退出;
(5) 若節點n不可擴充,則轉第(2)步;
(6) 擴充節點n,將其不在Closed表和
Open表中的子節點(判重)放入Open表的尾部
,並為每一個子節點設定指向父節點的指標(
或記錄節點的層次),然後轉第(2)步。

 

一層一層的往深了的搜尋,直到遇到所求解。那麼深度就是最短步數,還有要注意判重,其中visited數組就起到了判重的作用。

 

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 int n, k; 7 const int maxn = 100000; 8 int visited[maxn + 10];    //判重標記 9 struct Step10 {11     int x;12     int steps;13     Step(int xx, int s):x(xx), steps(s){}14 };15 queue<Step> q;16 int main(void)17 {18     scanf("%d%d", &n, &k);19     memset(visited, 0, sizeof(visited));20     q.push(Step(n, 0));21     visited[n] = 1;22     while(!q.empty())23     {24         Step s = q.front();25         if(s.x == k)26         {//找到目標27             printf("%d\n", s.steps);28             return 0;29         }30         else31         {32             if(s.x - 1 >= 0 && !visited[s.x-1])33             {34                 q.push(Step(s.x-1, s.steps+1));35                 visited[s.x-1] = 1;36             }37             if(s.x + 1 <= maxn && !visited[s.x+1])38             {39                 q.push(Step(s.x+1, s.steps+1));40                 visited[s.x+1] = 1;41             }42             if(s.x*2 <= maxn && !visited[s.x*2])43             {44                 q.push(Step(s.x*2, s.steps+1));45                 visited[s.x*2] = 1;46             }47             q.pop();48         }49     }50     return 0;51 }
代碼君

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.