POJ 3984 迷宫问题

迷宫问题

定义一个二维数组: 

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)


小技巧: 递归打印
 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 #include <queue>
 5 #include <cstdio>
 6 
 7 using namespace std;
 8 
 9 int maze[5][5];
10 int vis[5][5];
11 int dx[] = { 1,-1,0,0 };
12 int dy[] = { 0,0,1,-1 };
13 pair<int, int> father[6][6];    // father[i][j]表示点(i, j)的父节点的坐标 
14 
15 struct node
16 {
17     int x, y;
18 };
19 
20 void print(pair<int,int> p)
21 {
22     if (p.first == 0 && p.second == 0)
23         return;
24     else
25     {
26         print(father[p.first][p.second]);
27         printf("(%d, %d)
", father[p.first][p.second].first, father[p.first][p.second].second);
28     }
29 }
30 
31 
32 int main()
33 {
34     for (int i = 0; i < 5; ++i)
35         for (int j = 0; j < 5; ++j)
36             cin >> maze[i][j];
37     memset(vis, 0, sizeof(vis));
38 
39     node nod;
40     nod.x = nod.y = 0;
41     node t, p;
42     queue<node> Q;
43     Q.push(nod);
44     vis[0][0] = 1;
45 
46     while (!Q.empty())
47     {
48         t = Q.front();
49         Q.pop();
50 
51         if (t.x == 4 && t.y == 4)
52         {
53             print(make_pair(4, 4));
54             cout << "(4, 4)" << endl;
55             break;
56         }
57 
58         for (int i = 0; i < 4; ++i)
59         {
60             int xx = t.x + dx[i];
61             int yy = t.y + dy[i];
62 
63             if (xx >= 0 && xx < 5 && yy >= 0 && yy < 5 && maze[xx][yy] != 1 && !vis[xx][yy])
64             {
65                 vis[xx][yy] = 1;
66                 p.x = xx;
67                 p.y = yy;
68                 father[p.x][p.y] = make_pair(t.x, t.y);
69                 Q.push(p);
70             }
71         }
72     }
73 
74 
75     return 0;
76 }
原文地址:https://www.cnblogs.com/FengZeng666/p/10401627.html