码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3984 迷宫问题

时间:2015-10-05 14:09:00      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享
 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)\n", 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)\n");
51     bfs(0, 0);
52     printf("(4, 4)\n");
53     return 0;
54 }
View Code

 

POJ 3984 迷宫问题

标签:

原文地址:http://www.cnblogs.com/loveprincess/p/4855604.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!