题目信息
迷宫有一个入口,一个出口。一个人从入口走进迷宫,目标是找到出口。阴影部分和迷宫的外框为墙,每一步走一格,每格有四个可走的方向,探索顺序为地图方向:南(下)、东(右)、北(上)、西(左)。
输入
输入迷宫数组。第一行数据表示一个 n*n (n<=100)
的迷宫;第二行开始的n行为迷宫数据。其中:0表示路,1表示墙,起点在左上角<1,1>
的位置,终点在右下角 <n,n>
的位置。
输出
若有解,输出从入口到出口的一条路径,否则输出 there is no solution!
测试样例
测试样例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>
测试样例2
4 4
0 0 1 0
1 0 1 1
0 0 0 1
0 1 0 1
There is no solution!
解答
#include <cstring>
#include <iostream>
using namespace std;
bool map[105][105]; //地图
bool vis[105][105]; //判重
int dir[4][2] = {{-1, 0},
{1, 0},
{0, -1},
{0, 1}};//四个方向
int N;
struct node
{
int x, y; //坐标
int c; //上一点
} queue[105 * 105];
void print(int head)
{
while (queue[head].c != -1)
{
print(queue[head].c);
cout << "<" << queue[head].x + 1 << "," << queue[head].y + 1 << ">" << " ";
return;
}
printf("<1,1> ");
}
int bfs(int x, int y)
{
int head = 0, tail = 1;
//队列中第一个便是左上角的点,它的坐标(0,0)。前导无
queue[0].x = 0;
queue[0].y = 0;
queue[0].c = -1;
struct node now;//取一个中间值点
while (head < tail)
{//如果头小于尾
if (queue[head].x == N - 1 && queue[head].y == N - 1)
{//终点判定点条件,如果走到了最后
return head;
}
for (int i = 0; i < 4; i++)
{//现在向0,1,2,3四个方向去走
now.x = queue[head].x + dir[i][0];
now.y = queue[head].y + dir[i][1];
now.c = head;//找到了现在点的位置
if (now.x >= 0 && now.x < N && now.y >= 0 && now.y < N)
{//如果这个点符合在地图内
if (!vis[now.x][now.y] && !map[now.x][now.y])
{//如果没有遍历过,且地图中是(路0)
vis[now.x][now.y] = 1;//将其更改为遍历过
queue[tail] = now;//队尾增添当前元素
tail++;
}
}
}
head++;//四个方向遍历完了头增加一个
}
return 0;
}
int main()
{
//freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
cin >> N >> N;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{//先将点都输入到地图中
cin >> map[i][j];
}
}
memset(vis, 0, sizeof(vis));
int head = bfs(0, 0);
if (head == 0)
{
cout << "There is no solution!";
}
else
{
print(head);
}
cout << endl;
return 0;
}