十二、迷宫问题
题目描述
迷宫有一个入口,一个出口。一个人从入口走进迷宫,目标是找到出口。阴影部分和迷宫的外框为墙,每一步走一格,每格有四个可走的方向,探索顺序为地图方向:南(下)、东(右)、北(上)、西(左)。
-
输入:输入迷宫数组。第一行数据表示一个 n*n (n<=100)的迷宫;第二行开始的n行为迷宫数据。 其中:0表示路,1表示墙,起点在左上角 <1,1> 的位置,终点在右下角 <n,n> 的位置。
-
输出:若有解,输出从入口到出口的一条路径,否则输出 there is no solution!
例(上图所示的迷宫数组)
输入:
4 4
0 0 1 0
0 1 0 1
0 0 0 0
0 1 0 0
输出:<1,1> <2,1> <3,1> <3,2> <3,3> <4,3> <4,4>
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 4 4 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 | <1,1> <2,1> <3,1> <3,2> <3,3> <4,3> <4,4> | 1秒 | 64M | 0 |
测试用例 2 | 4 4 0 0 1 0 1 0 1 1 0 0 0 1 0 1 0 1 | There is no solution! | 1秒 | 64M | 0 |
测试用例 3 | 8 8 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0 0 0 0 1 1 1 0 1 0 1 1 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 | <1,1> <1,2> <2,2> <3,2> <3,1> <4,1> <5,1> <5,2> <5,3> <6,3> <6,4> <6,5> <7,5> <8,5> <8,6> <8,7> <8,8> | 1秒 | 64M | 0 |
解题思路
迷宫问题是大家学习深度优先搜索(DFS)和广度优先搜索(BFS)的经典问题之一,相信大家在参加集训的时候肯定都学习过了,也都有对应的模板进行解答。针对此题,稍微改改代码即可找到通过迷宫的路径。
一般的迷宫问题都是求最终的路径长度,而此题需要输出具体走过的路径。因此我们设置一个辅助结构 Position
来进行路径的存储,最后输出 vector<Position>
中存储的具体路径即可。
考虑一种极端情况是,当终点是 1 的时候,是没有任何一条的路径可以通向终点的,这种情况直接输出 There is no solution!
,但是测试用例里似乎没有出现这种情况,因此下面的代码把它注释了。
上机代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int map[110][110]; //模拟迷宫
int visit[110][110];//visit标记该位置是否走过
int n = 0, m = 0;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { -1,0,1,0 };
int sum = -9999;
int num = 1;
//设置一个辅助结构存储对应路径
struct Position
{
int x;
int y;
};
vector<Position>road;
int dfs(int x, int y)
{
sum = max(sum, num);
Position tmp;
tmp.x = x;
tmp.y = y;
road.push_back(tmp);
visit[x][y] = 1;
if (x == n && y == m)
{
sum = min(sum, num);
return 1;
}
for (int i = 0; i<4; i++)
{
int tx = x + dx[i];
int ty = y + dy[i];
if (!visit[tx][ty] && !map[tx][ty] && tx >= 1 && tx <= m && ty >= 1 && ty <= n)
{
//符合条件则继续搜索
num++;
if (dfs(tx, ty))
return 1;
road.pop_back(); //返回原状态
visit[tx][ty] = 0; //返回原状态
num--;
}
}
return 0;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
scanf("%d", &map[i][j]);
}
}
// if (map[n][m] == 1)
// {
// printf("There is no solution!\n");
// return 0;
// }
dfs(1, 1);
if (sum<n + m - 1) { //没有墙的话,迷宫走到终点的最少步数是n+m-1
printf("There is no solution!\n");
return 0;
}
else
{
for (int i = 0; i < road.size(); i++)
{
printf("<%d,%d> ", road[i].x, road[i].y);
}
printf("\n");
}
return 0;
}