迷宫问题 广度优先算法
问题:用一个二维数组来存储迷宫,数组中的每个元素的值只取0或1,其中0表示此路可通,1表示此路不通。对于上例的迷宫可存储如图:
假定迷宫入口坐标为(1,1)
输出为路径
实现代码如下:
/*
迷宫问题(广度优先算法)
作者:Lumao
版本:2021/3/28 0.0版
方法:C++ 队列 栈 数组 结构体 循环 广度优先算法
目标:找一条出路即结束
要点:队列的类型step step类型中的pre指针指向前驱,找到路径
小结:感觉有疏漏的情况
*/
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
#define m 6
#define n 8
int theMap[][n + 2] = {//原地图
{ 1,1,1,1,1,1,1,1,1,1 },
{ 1,0,1,1,1,0,1,1,1,1 },
{ 1,1,0,1,0,1,0,1,0,1 },
{ 1,0,1,0,0,1,1,1,1,1 },
{ 1,0,1,1,1,0,0,1,1,1 },
{ 1,1,0,0,1,1,0,0,0,1 },
{ 1,0,1,1,0,0,1,1,0,1 },
{ 1,1,1,1,1,1,1,1,1,1 }
};
int maze[m + 2][n + 2];//地图
struct step
{
int x, y;
step*pre;
};
struct step Move[8]{
//step 类型数组Move代表8个前进方向
{ 0,1,NULL },
{ 1,1,NULL },
{ 1,0,NULL },
{ 1,-1,NULL},
{ 0,-1,NULL},
{ -1,-1,NULL},
{ -1,0,NULL},
{ -1,1,NULL}
};
void initialize(int maze[m + 2][n + 2])//初始化地图
{
for (int i = 0; i < m + 2; i++)
for (int j = 0; j < n + 2; j++)
maze[i][j] = theMap[i][j];
}
void Restore(int maze[m + 2][n + 2])//恢复原地图
{
initialize(maze);
}
void PrintPath(step* temp1)//打印路径
{
stack<step>s;
while (temp1 != NULL)
{
s.push(*temp1);
temp1 = temp1->pre;
}
while (!s.empty())
{
cout << "(" << s.top().x << "," << s.top().y << ")" << endl;
s.pop();
}
cout << endl;
}
int MazePath()
{
queue<step*>q;//用于广搜的队列
step*temp1, *temp2;
int x, y, loop;
temp1 = new step;
temp1->x = 1;
temp1->y = 1;
temp1->pre = NULL;
maze[1][1] = -1;//标志入口已经到达过
q.push(temp1);//将入口入列
while (!q.empty())//队列不空,继续广搜
{
temp2 = q.front();
q.pop();
for (loop = 0; loop < 8; loop++)
{
x = temp2->x + Move[loop].x;
y = temp2->y + Move[loop].y;
if (maze[x][y] == 0)
{
temp1 = new step;
temp1->x = x;
temp1->y = y;
temp1->pre = temp2;//设置前驱指针
maze[x][y] = -1;//标志该位置已到达过
q.push(temp1);
if ((x == m) && (y == n))//到达出口
{
cout << "The path is:" << endl;
PrintPath(temp1);//从temp1开始往回指向即为路径
Restore(maze);//恢复迷宫
return 1;//找到路径结束函数
}
}
}
}
return 0;//没有找到路径
}
int main()
{
initialize(maze);
MazePath();
system("pause");
return 0;
}