#include<iostream>
#include<stack>
using namespace std;
#define MaxCol 10
#define MaxRow 10
struct Seat//定义一个表示位置的结构体
{
Seat(int x,int y)
:_x(x)
,_y(y)
{}
int _x;
int _y;
};
class Maze
{
public:
Maze(int arr[][MaxCol], int Row, int Col)
{
_map = new int*[MaxRow];//先开辟行的空间
for(int i = 0; i < MaxRow; ++i)
{
_map[i] = new int[MaxCol];//再在每行开辟列的空间
for(int j = 0; j < MaxCol; j++)
{
_map[i][j] = arr[i][j];
}
}
}
void PrintMaze()//打印迷宫
{
for(int i = 0;i < MaxRow;i++)
{
for(int j = 0;j < MaxCol;j++)
{
cout<<_map[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
~Maze()
{
for(int i = 0; i < MaxCol; ++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 >= MaxRow || s._y < 0 || s._y >= MaxCol)//出口
return true;
return false;
}
bool PassMaze(Seat& s)//走迷宫
{
if(s._x < 0 || s._x >= MaxRow || s._y < 0 || s._y >= MaxCol)//防止数组越界
return true;
if(IsPass(s))//若当前位置为通路
{
_map[s._x][s._y] = 2;//标记当前走过的位置为2
//将当前位置前后左右坐标给出
Seat front(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(front))//利用递归来探路
{
_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[MaxRow][MaxCol] = {
{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, 1, 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,MaxRow,MaxCol);
maze.PrintMaze();
Seat s(9,6);//给出入口
maze.PassMaze(s);//走迷宫
maze.PrintMaze();//将走过的路线打印出来
system("pause");
return 0;
}
附上结果截图
其实在走迷宫那部分中的递归回溯算法就是一种探路的思想,看前后左右哪个节点可以走通。