POJ 3984 迷宫问题

解题思路:打印路径的模板题,有点意思。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn = 5;
 6 int mapp[maxn][maxn], dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
 7 int f = 0, r = 1; //f为头指针,r为尾指针
 8 
 9 struct node{
10     int x, y, pre; //pre存储前一步的下标,即存储路径
11 }q[maxn*maxn]; //注意这里q的大小不是maxn,而是maxn*maxn
12 
13 void print(int i)
14 {
15     if(q[i].pre != -1) //初始化时做过标记,当q[i].pre == -1表示已经输出完毕
16     {
17         print(q[i].pre); //这里的递归很巧妙,好好品味。
18         printf("(%d, %d)
", q[i].x, q[i].y);
19     }
20     return ;
21 }
22 
23 void bfs(int x, int y)
24 {
25     q[f].x = x, q[f].y = y, q[f].pre = -1;
26 
27     while(f < r)
28     {
29         for(int i = 0; i < 4; i++)
30         {
31             int xx = q[f].x + dir[i][0];
32             int yy = q[f].y + dir[i][1];
33 
34             if(xx < 0 || xx >= 5 || yy < 0 || yy >= 5 || mapp[xx][yy]) continue;
35             mapp[xx][yy] = 1; //标记为已经走过
36             q[r].x = xx, q[r].y = yy, q[r].pre = f, r++;
37 
38             if(xx == 4 && yy == 4) print(f); //走到终点时倒退回去打印路径。
39         }
40         f ++; //一个元素出队列
41     }
42     return ;
43 }
44 
45 int main()
46 {
47     for(int i = 0; i < 5; i++)
48     for(int j = 0; j < 5; j++) scanf("%d", &mapp[i][j]);
49 
50     printf("(0, 0)
");
51     bfs(0, 0);
52     printf("(4, 4)
");
53     return 0;
54 }
View Code
原文地址:https://www.cnblogs.com/loveprincess/p/4855604.html