POJ 3984 迷宮問題

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   art   

第二道廣搜的問題

雖然思路很清晰,可真要自己把代碼敲出來並不是一件容易的事

用一維數組類比一個隊列,head和tail分別記錄隊首和隊尾

先將迷宮的起點入隊,然後向四個方向拓展,如果沒有出界或者沒有遇到牆壁,那麼入隊,然後隊首出隊

知道搜到迷宮的出口為止

 

 1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6  7 struct Point 8 { 9     int x, y, pre;10 }queue[30];11 12 int map[7][7];13 int head = 0, tail = 1;14 int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};15 16 void output(int i)17 {18     if(queue[i].pre != -1)19     {20         output(queue[i].pre);21         printf("(%d, %d)\n", queue[i].x, queue[i].y);22     }23 }24 25 int main(void)26 {27     #ifdef LOCAL28         freopen("3984in.txt", "r", stdin);29     #endif30 31     for(int i = 0; i < 5; ++i)32         for(int j = 0; j < 5; ++j)33             scanf("%d", &map[i][j]);34     //將迷宮的起點入隊35     queue[0].x = queue[0].y = 0;36     queue[0].pre = -1;37     map[0][0] = 1;38     printf("(0, 0)\n");39     while(head < tail)40     {41         for(int i = 0; i < 4; ++i)42         {43             int xx = queue[head].x + dir[i][0];44             int yy = queue[head].y + dir[i][1];45             if(xx<0 || xx >=5 || yy<0 || yy>=5 || map[xx][yy])46                 continue;47             map[xx][yy] = 1;    //標記已經走過48             queue[tail].x = xx;49             queue[tail].y = yy;50             queue[tail++].pre = head;51             if(xx == 4 && yy == 4)52                 output(head);//找到要搜尋的目標,開始輸出53         }54         ++head;//隊首元素出隊55     }56     printf("(4, 4)\n");57     return 0;58 }
代碼君

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.