標籤: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 }代碼君