bfs—迷宫问题—poj3984

迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 20591   Accepted: 12050

http://poj.org/problem?id=3984

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 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

bfs过程中记录每个点的上一个点坐标,最后从终点找回到起点,利用栈逆序输出。
 1 #include<iostream>
 2 #include<cstring>
 3 #include<string>
 4 #include<queue>
 5 #include<stack>
 6 #include<set>
 7 using namespace std;
 8 
 9 const int MAX=5;
10 struct Node
11 {
12     int x,y,pace;
13     bool c;
14     int prex,prey;//记录上一个点的坐标
15 }maze[MAX][MAX],t;
16 int dre[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//方向
17 
18 int main()
19 {
20     for(int i=0;i<5;i++)
21         for(int j=0;j<5;j++)
22         {
23             cin>>maze[i][j].c;
24             maze[i][j].x=i;
25             maze[i][j].y=j;
26         }
27     queue<Node> Q;
28     stack<Node> St;
29     int X,Y;
30     Q.push(maze[0][0]);
31     while(!Q.empty())
32     {
33         t=Q.front();
34         if(t.x==4&&t.y==4)//到达右下角
35         {
36             St.push(t);
37             while(t.x!=0||t.y!=0)//根据上一个点坐标把一条路所有点压入栈
38             {
39                 t=maze[t.prex][t.prey];
40                 St.push(t);
41             }
42             while(!St.empty())//把点逆序输出
43             {
44                 cout<<"("<<St.top().x<<", "<<St.top().y<<")
";
45                 St.pop();
46             }
47         }
48         Q.pop();
49         for(int i=0;i<4;i++)
50         {
51             X=t.x+dre[i][0];
52             Y=t.y+dre[i][1];
53             if(X>=0&&X<5&&Y>=0&&Y<5&&maze[X][Y].c==0&&!maze[X][Y].pace)
54             {
55                 maze[X][Y].pace=t.pace+1;
56                 maze[X][Y].prex=t.x;//记录上一个点坐标
57                 maze[X][Y].prey=t.y;
58                 Q.push(maze[X][Y]);
59             }
60         }
61     }
62     return 0;
63 }
原文地址:https://www.cnblogs.com/Fresh--air/p/6661424.html