POJ 3984 迷宫问题

POJ 3984 迷宫问题

Time Limit: 1000MS    Memory Limit: 65536K

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找最短路径,然后再BFS回溯,倒序输出即可。

 

代码 C++

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <queue>
 4 #define INF 0x7F7F7F7F
 5 struct Point{
 6     int x, y;
 7 }now, nxt, opt[105];
 8 int map[15][15], fx[8] = { 1, 0, -1, 0, 0, -1, 0, 1 };
 9 int main(){
10     int i, j, tmp;
11     for (i = 1; i <= 5; ++i) for (j = 1; j <= 5; ++j){
12         scanf("%d", &tmp);
13         if (!tmp) map[i][j] = INF;
14     }
15     std::queue<Point> q;
16     now.y = now.x = 1;
17     q.push(now); map[1][1] = 2;
18     while (!q.empty()){
19         now = q.front(); q.pop();
20         tmp = map[now.y][now.x] + 1;
21         for (i = 0; i < 8; i += 2){
22             nxt.y = now.y + fx[i]; nxt.x = now.x + fx[i + 1];
23             if (map[nxt.y][nxt.x] == INF){
24                 map[nxt.y][nxt.x] = tmp; q.push(nxt);
25             }
26         }
27     }
28     now.y = now.x = 5;
29     q.push(opt[0] = now); j = 1;
30     while (!q.empty()){
31         now = q.front(); q.pop();
32         tmp = map[now.y][now.x] - 1;
33         for (i = 0; i < 8; i += 2){
34             nxt.y = now.y + fx[i]; nxt.x = now.x + fx[i + 1];
35             if (map[nxt.y][nxt.x] == tmp){
36                 opt[j++] = nxt; q.push(nxt); break;
37             }
38         }
39     }
40     for (i = j - 1; ~i; --i) printf("(%d, %d)\n", opt[i].y - 1, opt[i].x - 1);
41     return 0;
42 }

 

posted @ 2017-02-12 18:38  Simon_X  阅读(226)  评论(0编辑  收藏  举报