# ifndef MAZE_H
# define MAZE_H
# include<iostream>
# include"stack.h"
using namespace std;
class position{
public:
int x;
int y;
};
stack<position> *path;
class Maze
{
public:
void welcom();
void inputmaze();
bool findpath();
void outputmaze();
protected:
int **maze;
int n;
};
void Maze::welcom()
{
cout<<"请输入迷宫矩阵的大小:"<<endl;
cin>>n;
}
void Maze::inputmaze()
{
maze=new int *[n+2];
for(int i=0;i<n+2;i++)
maze[i]=new int [n+2];
//以上为动态分配数组空间
for(int i=0;i<=n+1;i++)
{
maze[i][0]=1;
maze[i][n+1]=1;
maze[0][i]=1;
maze[n+1][i]=1;
}
//以上为在迷宫周围立上围墙
cout<<"输入迷宫矩阵"<<endl;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>maze[i][j];
}
//以下为核心代码,以深度优先搜索为代码思想
bool Maze::findpath()
{
path=new stack<position>;
position offset[4];
offset[0].x=1;offset[0].y=0;//right
offset[1].x=0;offset[1].y=1;//down
offset[2].x=-1;offset[2].y=0;//left
offset[3].x=0;offset[3].y=-1;//up
position here;
here.x=1;
here.y=1;
maze[1][1]=2;//起点做标记
int option=0;
int lastoption=3;
while(here.x!=n||here.y!=n)
{
int r,c;
while(option<=lastoption)
{
r=here.x+offset[option].x;
c=here.y+offset[option].y;
if(maze[c][r]==0)
break;
option++;
}
if(option<=lastoption)
{
path->push(here);
here.x=r;
here.y=c;
maze[c][r]=2;//走过的点做标记
option=0;
}
else{
if(path->empty())
return false;
position next=path->Top();
path->pop();
if(here.y==next.y)
option=2+next.x-here.x;
else
option=3+next.y-here.y;
maze[here.y][here.x]=-1;//走不通,去掉标记。
here=next;
}
}
return true;
}
void Maze::outputmaze()
{
position here;
if(findpath())
{
for(int i=0;i<=n+1;i++)
{
for(int j=0;j<=n+1;j++)
{
if(maze[i][j]==1)
cout<<'#';
if(maze[i][j]==2)
cout<<'*';
if(maze[i][j]==-1||maze[i][j]==0)
cout<<" ";
}
cout<<endl;
}
}
else cout<<"没有路径"<<endl;
}
# endif
# include<iostream>
# include"maze.h"
using namespace std;
int main()
{
Maze s;
s.welcom();
s.inputmaze();
s.outputmaze();
return 0;
}