#include<iostream.h>
#include<stdlib.h>
#define m 8
#define n 8
#define maxsize 100
int maze[m+2][n+2];
typedef struct//试探方向
{int x,y;
}item;
item move [4]={{0,1},{1,0},{0,-1},{-1,0}};
typedef struct//栈元素设计
{int x,y,d;
}datetype;
typedef struct//栈
{datetype data[maxsize];
int top;
}SeqStack;
SeqStack *Init_SeqStack()//置空栈
{
SeqStack *s;
s=(SeqStack *)malloc(sizeof(SeqStack));
s->top=0;
return s;
}
int Empty_SeqStack(SeqStack *s)//判栈空
{
if(s->top==0)return 1;
else return 0;
}
int Push_SeqStack(SeqStack *s,datetype x)//入栈
{
if(s->top==maxsize-1)return 0;
else
{
s->top++;
s->data[s->top]=x;
return 1;
}
}
int Pop_SeqStack(SeqStack *s,datetype *x)//出栈
{
if(Empty_SeqStack(s))return 0;
else
{
*x=s->data[s->top];
s->top--;
return 1;
}
}
int path(SeqStack *s)//寻找路径
{
datetype temp;
int x,y,d,i,j;
temp.x=1; temp.y=1; temp.d=-1;
Push_SeqStack (s,temp);
while (!Empty_SeqStack(s))
{
Pop_SeqStack (s,&temp);
x=temp.x;y=temp.y;d=temp.d+1;
while (d<4)
{
i=x+move[d].x;j=y+move[d].y;
if (maze[i][j]==0)
{
temp.x=x;temp.y=y;temp.d=d;
Push_SeqStack (s,temp);
x=i;y=j;maze[x][y]=-1;
if (x==m&&y==n) return 1;
else d=0;
}
else d++;
}
}return 0;
}
void print(SeqStack *s)//输出栈
{
int i;
for(i=1;i<=s->top;i++)
{
cout<<"("<< s->data[i].x<<","<<s->data[i].y<<","<<s->data[i].d<<")";
if(i<s->top)cout<<"→";
if(i%3==0) cout<<"\n";
}
cout<<"\n";
}
int main()
{
SeqStack *s ;
int i,k,j,w;
do
{
cout<<"1--随机生成迷宫\n";
cout<<"0--退出\n";
cin>>w;
switch(w)
{
case 1:for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
{
maze[i][j]=rand()%2;//随机数组
}
maze[1][1]=0;maze[8][8]=0;//入口和出口
for(i=0;i<m+2;i++) //添加外围
{
maze[i][0]=8;maze[i][n+1]=8;
}
for (j=0;j<n+2;j++)
{
maze[0][j]=8;maze[m+1][j]=8;
}
cout<<"随机生成的迷宫图为:\n\n";
for(i=0;i<m+2;i++)
{
for(j=0;j<n+2;j++)
cout<<maze[i][j]<<" ";
cout<<"\n";
}
s=Init_SeqStack();
k=path(s);
if (k==1)
{
if(k==1)
cout<<"迷宫有路:\n";
print(s);
for(i=0;i<m+2;i++)
{
for(j=0;j<n+2;j++)
{
if(maze[i][j]==-1)
cout<<" "<<maze[i][j];
else cout<<" "<<maze[i][j];
}
cout<<"\n";
}
}
else cout<<"迷宫没路\n\n";
break;
}
}while(w);
return 0;
}