迷宫生成算法(2)深度优先搜索
由于上次的实现中存在着一些问题,因此这次还是使用深度优先搜索,改掉下面这几个问题:
- 显示迷宫时,直接输出数字0和1显得不够直观。
- 递归部分的解释不够严谨,实现也很混乱,这次着重重写了这一部分。
- 实践表明迷宫的尺寸只能是奇数,如果是偶数会出现一行或者一列遍历不到,因此我们检查用户输入,对输入的偶数直接加1。
除了这些之外,还修改了一下迷宫类的定义,把和坐标有关的成员变量都用pair封装成一组,并且修改了一些函数的定义。
下面是代码:
#include<iostream>
#include<vector>
#include<memory>
#include<algorithm>
using namespace std;
pair<int, int> input()
{
cout << "please input the size of the maze:" << endl;
int row, column;
cin >> row >> column;
row = row % 2 == 0 ? row + 1 : row;
column = column % 2 == 0 ? column + 1 : column;
return {
row, column };
}
class Maze
{
private:
unique_ptr<int *[]> mazePtr;
pair<int, int> size;
pair<int, int> entry;
pair<int, int> start;
vector<pair<int, int>> direction = {
{
1,0},{
0,1},{
-1,0},{
0,-1} };
public:
Maze(int x, int y);
ostream& print();
bool createMaze();
private:
bool