迷宫求解(栈实现)
自己写的,外面别人的看了一下,感觉不少都是递归解决这类问题的,然后我尝试用非递归解决的。混合了类的运用,多说不如直接上代码了。
#include<iostream>
#include<stdio.h>
#include<stack>
#define M 8
using namespace std;
struct Pos {
int i;
int j;
};
class Maze{
public:
Maze()=default;
Maze(int a1,int b1,int a2,int b2)
{
start_.i=a1;
start_.j=b1;
end_.i=a2;
end_.j=b2;
}
~Maze()=default;
void CreateMaze();
void PrintMaze();
bool MakeIt();
private:
int Ma_ze[M][M];
Pos start_;
Pos end_;
};
void Maze::CreateMaze( )
{
int i=,j=;
int a=;
for (i=;i<M;i++)
{
for (j=;j<M;j++)
{
cin>>a;
Ma_ze[i][j]=a;
}
}
Ma_ze[start_.i][start_.j]=;
}
void Maze::PrintMaze( )
{
int i=,j=;
for (i=;i<M;i++)
{
for (j=;j<M;j++)
{
if (Ma_ze[i][j]==)
{
cout<<"●";
}
else if(Ma_ze[i][j]==)
{
cout<<" ";
}
else if (Ma_ze[i][j]==)
{
cout<<"**";
}
}
cout<<endl;
}
}
bool Maze::MakeIt()//完成路径寻找
{
bool issuccess=false;
stack <Pos> make;
Pos alit,blit;
make.push(start_);
while ()
{
if (make.empty()==true)
{
break;
}
alit=make.top();
//cout<<alit.i<<" "<<alit.j<<endl;
//make.pop();
if (Ma_ze[alit.i+][alit.j]==)
{
blit.i=alit.i+;
blit.j=alit.j;
Ma_ze[alit.i+][alit.j]=;
if (blit.i==end_.i&&blit.j==end_.j)
{
issuccess=true;
break;
}
make.push(blit);
}
else if (Ma_ze[alit.i][alit.j+]==)
{
blit.i=alit.i;
blit.j=alit.j+;
Ma_ze[alit.i][alit.j+]=;
if (blit.i==end_.i&&blit.j==end_.j)
{
issuccess=true;
break;
}
make.push(blit);
}
else if (Ma_ze[alit.i-][alit.j]==)
{
blit.i=alit.i-;
blit.j=alit.j;
Ma_ze[alit.i-][alit.j]=;
if (blit.i==end_.i&&blit.j==end_.j)
{
issuccess=true;
break;
}
make.push(blit);
}
else if (Ma_ze[alit.i][alit.j-]==)
{
blit.i=alit.i;
blit.j=alit.j-;
Ma_ze[alit.i][alit.j-]=;
if (blit.i==end_.i&&blit.j==end_.j)
{
issuccess=true;
break;
}
make.push(blit);
}
else
{
make.pop();
}
}
return issuccess;
}
int main()
{
Maze m(,,,);
freopen("maze.txt","r",stdin);
m.CreateMaze();
m.PrintMaze();
if (m.MakeIt()==true)
{
m.PrintMaze();
}
else
{
cout<<"error"<<endl;
}
}
这是测试用的数据,“2”表示墙壁,“0”表示可以走。
2 2 2 2 2 2 2 2
2 0 0 2 0 2 0 2
2 2 0 0 0 0 0 2
2 0 0 2 0 2 0 2
2 2 2 2 0 2 0 2
2 2 0 0 0 2 0 2
2 0 0 2 0 0 0 2
2 2 2 2 2 2 2 2
反思就是代码还有很多可以写的更简洁的地方,比较懒想等到以后了。