您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】迷宫(递归)

2017-08-19 15:28 232 查看
代码如下:

#include <iostream>
#include <stack>
using namespace std;

#define MAX_ROW 10  //宏定义行
#define MAX_COL 10  //宏定义列

struct Seat
{
Seat(int x, int y)
:_x(x)
, _y(y)
{}
int _x;
int _y;
};
class Maze
{
public:
Maze(int arr[][MAX_COL], int Row, int Col)
{
_map = new int*[MAX_ROW];//先开辟行的空间
for (int i = 0; i < MAX_ROW; ++i)
{
_map[i] = new int[MAX_COL];//再在每行开辟列的空间
for (int j = 0; j < MAX_COL; j++)
{
_map[i][j] = arr[i][j];
}
}
}

void PrintMaze()//打印迷宫
{
for (int i = 0; i < MAX_ROW; i++)
{
for (int j = 0; j < MAX_COL; j++)
{
cout << _map[i][j] << " ";
}
cout << endl;
}
cout << endl;
}

~Maze()
{
for (int i = 0; i < MAX_COL; ++i)//先销毁每行中开辟的空间
{
delete[] _map[i];
}
delete _map;
}

bool IsPass(Seat s)//判断当前位置是否为通路
{
if (1 == _map[s._x][s._y])
return true;

if (s._x < 0 || s._x >= MAX_ROW || s._y < 0 || s._y >= MAX_COL)//出口
return true;

return false;
}

bool PassMaze(Seat& s)//走迷宫
{
if (s._x < 0 || s._x >= MAX_ROW || s._y < 0 || s._y >= MAX_COL)//防止数组越界
return true;

// 是否为出口
if (IsPass(s))//若当前位置为通路
{
_map[s._x][s._y] = 2;//标记当前走过的位置为2
//将当前位置前后左右坐标给出
Seat up(s._x - 1, s._y);
Seat left(s._x, s._y - 1);
Seat right(s._x, s._y + 1);
Seat down(s._x + 1, s._y);

if (PassMaze(up)) //朝上走
{
_map[s._x][s._y] = 2;
return true;
}
if (PassMaze(left)) //朝左走
{
_map[s._x][s._y] = 2;
return true;
}
if (PassMaze(right)) //朝右走
{
_map[s._x][s._y] = 2;
return true;
}
if (PassMaze(down)) //朝下走
{
_map[s._x][s._y] = 2;
return true;
}
_map[s._x][s._y] = 3;//若上下左右均走不通,则回退回来并且将原来位置标记为3,不再走这里
}
return false;
}
private:
int **_map;
};

int main()
{
int MapArr[MAX_ROW][MAX_COL] = {
{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }
};

Maze maze(MapArr, MAX_ROW, MAX_COL);
maze.PrintMaze();
Seat s(9, 6); //迷宫入口
maze.PassMaze(s);
maze.PrintMaze();

return 0;
}


运行结果:



这样,一个简易的递归实现迷宫就完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息