標籤:
廣度優先演算法:
類比隊列:資料量較小,需要列印路徑座標
STL隊列:資料量較大,只需要列印步數
迷宮問題
Description
定義一個二維數組:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫著走或豎著走,不能斜著走,要求編程式找出從左上方到右下角的最短路線。
Input
一個5 × 5的二維數組,表示一個迷宮。資料保證有唯一解。
Output
左上方到右下角的最短路徑,格式如範例所示。
Sample Input
0 1 0 0 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0
Sample Output
(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)
1 #include <stdio.h> 2 #include <iostream> 3 4 using namespace std; 5 6 const int MAX = 5; 7 const int x[] = { -1, 0, 1, 0 }; 8 const int y[] = { 0, 1, 0, -1 }; 9 10 struct point11 {12 int x, y, pre;13 point(){};14 point(int _x, int _y, int _pre) : x(_x), y(_y), pre(_pre){};15 };16 17 point que[MAX * MAX];18 int arr[MAX][MAX];19 bool vis[MAX][MAX];20 21 void BFS();22 void Print(int n);23 24 int main()25 {26 #ifdef OFFLINE27 freopen("input.txt", "r", stdin);28 freopen("output.txt", "w", stdout);29 #endif30 31 memset(que, 0, sizeof(que));32 memset(arr, 0, sizeof(arr));33 memset(vis, 0, sizeof(vis));34 35 for (int i = 0; i < MAX; i++)36 {37 for (int j = 0; j < MAX; j++)38 {39 scanf("%d", &arr[i][j]);40 }41 }42 43 BFS();44 45 return 0;46 }47 48 void BFS()49 {50 int qh = 0, qt = 0;51 que[qt++] = point(0, 0, -1);52 vis[0][0] = true;53 54 while (qh < qt)55 {56 if (que[qh].x == 4 && que[qh].y == 4)57 {58 Print(qh);59 return;60 }61 62 for (int i = 0; i < 4; i++)63 {64 int nx = que[qh].x + x[i], ny = que[qh].y + y[i], npre = qh;65 if (nx >= 0 && nx < MAX && ny >= 0 && ny < MAX && !arr[nx][ny] && !vis[nx][ny])66 {67 que[qt++] = point(nx, ny, npre);68 vis[nx][ny] = true;69 }70 }71 72 qh++;73 }74 75 return;76 }77 78 void Print(int n)79 {80 if (n == -1) return;81 Print(que[n].pre);82 printf("(%d, %d)\n", que[n].x, que[n].y);83 }View Code
廣度優先演算法:迷宮問題