广度优先搜索:
模拟队列:数据量较小,需要打印路径坐标
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 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0Sample 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 point 11 { 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 OFFLINE 27 freopen("input.txt", "r", stdin); 28 freopen("output.txt", "w", stdout); 29 #endif 30 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 }