广度优先搜索可以找到最短的走出迷宫的路径,看能不能走出迷宫很简单,由于广度优先搜索总是找到离某点最近的下一个点,找到的路径一定是最短路径,详见算法笔记上关于广度优先搜索的介绍,问题是如何输出走出迷宫的路径,我们可以申请一个和迷宫一样大的储存点信息的path二维数组,path中的任意元素为到达他之前的点的信息,然后输出path即可。
代码如下:
#include"pch.h"
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<queue>
#include<cstdio>
using namespace std;
//生成迷宫
const int HEIGHT = 10;
const int WIDTH = 10;
bool isFound = false;
int maze[HEIGHT][WIDTH];
void initialMaze()
{
maze[0][0] = 0;//入口
maze[HEIGHT - 1][WIDTH - 1] = 0;//出口
for (int i = 0; i < HEIGHT; i++)//用随机数0,1填充迷宫
{
for (int j = 0; j < WIDTH; j++)
{
if (i == 0 && j == 0)
continue;
if (i == HEIGHT - 1 && j == WIDTH - 1)
continue;
maze[i][j] = rand() % 2;
}
}
//展示生成的迷宫
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
cout << maze[i][j];
if (j != WIDTH - 1)
{
cout << " ";
}
else
{
cout << endl;
}
}
}
}
//生成方向
int directory[8][2] = { {0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1} };
//判断是否越界
bool isLeap(int x, int y)
{
return x >= 0 && x < WIDTH&&y >= 0 && y < HEIGHT;
}
//任意位置的结构体
struct point {
int x;
int y;
};
//声明用于存储路径的结构体
struct dir
{
int x;
int y;
int d;
};
//声明用于存储路径的队列
queue<dir> directoryQueue;
//迷宫循迹
dir path[HEIGHT][WIDTH];//记录迷宫的路径
int output[HEIGHT*WIDTH][3];
void mazeTravel(point start, point end, int maze[HEIGHT][WIDTH], int directory[8][2])
{
dir element;
dir tmp;
int i;
int j;
int d;
int a;
int b;
element.x = start.x;
element.y = start.y;
element.d = -1;
maze[start.x][start.y] = 2;
directoryQueue.push(element);
while (!directoryQueue.empty())
{
element = directoryQueue.front();
dir m = element;
directoryQueue.pop();
i = element.x;
j = element.y;
d = element.d + 1;
while (d < 8)
{
a = i + directory[d][0];
b = j + directory[d][1];
if (a == end.x&&b == end.y&&maze[a][b] == 0)
{
//储存前一个点的信息至path
dir temp = m;
temp.d = d;
path[a][b] = temp;
isFound = true;
return;
}
if (isLeap(a, b)&&maze[a][b]==0)
{
//储存前一个点的信息至path
dir temp = m;
temp.d = d;
path[a][b] = temp;
maze[a][b] = 2;
element.x = a;
element.y = b;
element.d = -1;
directoryQueue.push(element);
}
d++;
}
}
}
void printPath(point start, point end)
{
if (!isFound)
printf_s("The path is not found");
else
{
int step = 0;
dir q;
q.x = end.x;
q.y = end.y;
q.d = 886;
while (q.x != start.x || q.y != start.y)
{
output[step][0] = q.x;
output[step][1] = q.y;
output[step][2] = q.d;
int x = q.x;
int y = q.y;
q.x = path[q.x][q.y].x;
q.y = path[x][q.y].y;
q.d = path[x][y].d;
step++;
}
output[step][0] = q.x;
output[step][1] = q.y;
output[step][2] = q.d;
printf_s("The path is as follows: \n");
for (int i = step; i >= 0; i--)
{
printf_s("(%d,%d)", output[i][0], output[i][1]);
if (i != 0)
printf_s("->");
}
printf_s("\n");
}
}
int main()
{
srand(time(0));
initialMaze();
point a, b;
a.x = 0;
a.y = 0;
b.x = HEIGHT - 1;
b.y = WIDTH - 1;
mazeTravel(a, b, maze, directory);
printPath(a, b);
return 0;
}
实现效果如下(1代表围墙,0代表空地)