首先是栈的一些基本操作:定义、初始化、判断栈空、入栈、出栈
1.栈的定义
typedef struct
{
int row,col;//行与列
int dir; //下一步的方向
}Node;
typedef struct
{
int top; //栈顶指针
Node data[Maxsize];
//int len;
}SqStack;
typedef struct
{
int row,col;
}item;
2.栈的初始化
void InitStack(SqStack *p)
{
p->top=-1;
}
3.判断栈空
int EmptyStack(SqStack p)
{
if(p.top==-1)
return 1;
else return 0;
}
4.入栈
void PushStack(SqStack *p,Node e)
{
if(p->top==Maxsize-1)
{
printf("栈已满!\n");
return ;
}
p->top++;
p->data[p->top].row=e.row;
p->data[p->top].col=e.col;
p->data[p->top].dir=e.dir;
}
5.出栈
void PopStack(SqStack *p,Node *e)
{
if(p->top==-1)
{
printf("栈已空!\n");
return ;
}
e->row=p->data[p->top].row;
e->col=p->data[p->top].col;
e->dir=p->data[p->top].dir;
p->top--;
}
迷宫上下左右移动的四个方向:
dire[4]={{0,1},{1,0},{0,-1},{-1,0}};
完整代码如下:
#include<bits/stdc++.h>
using namespace std;
const int Maxsize=100;
//栈的定义
typedef struct
{
int row,col;//行与列
int dir; //下一步的方向
}Node;
typedef struct
{
int top; //栈顶指针
Node data[Maxsize];
//int len;
}SqStack;
typedef struct
{
int row,col;
}item;
//栈的初始化
void InitStack(SqStack *p)
{
p->top=-1;
}
//判断栈是否为空
int EmptyStack(SqStack p)
{
if(p.top==-1)
return 1;
else return 0;
}
//入栈
void PushStack(SqStack *p,Node e)
{
if(p->top==Maxsize-1)
{
printf("栈已满!\n");
return ;
}
p->top++;
p->data[p->top].row=e.row;
p->data[p->top].col=e.col;
p->data[p->top].dir=e.dir;
}
//出栈
void PopStack(SqStack *p,Node *e)
{
if(p->top==-1)
{
printf("栈已空!\n");
return ;
}
e->row=p->data[p->top].row;
e->col=p->data[p->top].col;
e->dir=p->data[p->top].dir;
p->top--;
}
//展示迷宫
void Print(int a[10][10])
{
int i,j;
printf("迷宫展示如下(1表示墙,0表示路):\n");
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
//求解一条迷宫通路
void PrintStack(SqStack p)
{
Node q;
printf("<-(8,8)");
while(!EmptyStack(p))
{
PopStack(&p,&q);
printf("<-(%d,%d)",q.row,q.col);
}
printf("\n");
}
void Anspath(int vis[10][10],item dire[4])
{
SqStack p;
Node q;
int row,col,dir,i,j;
InitStack(&p);
q.row=1; q.col=1; q.dir=-1; //起点初始化
PushStack(&p,q);
while(!EmptyStack(p))
{
PopStack(&p,&q);
row=q.row;
col=q.col;
dir=q.dir+1;
while(dir<4)//判断当前节点上下左右四个方向是否可走,可走则更新节点
{
i=row+dire[dir].row;
j=col+dire[dir].col;
if(vis[i][j]==0) //此节点是否走过
{
q.row=row;
q.col=col;
q.dir=dir;
PushStack(&p,q);
row=i;
col=j;
vis[row][col]=-1;
if(row==8&&col==8)
{
PrintStack(p);
return ;
}
else dir=0;
}
else dir++;
}
}
printf("迷宫无通路!\n");
return ;
}
int main(){
int a[10][10]={{1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}};
item dire[4]={{0,1},{1,0},{0,-1},{-1,0}};//上下左右四个移动方向
printf("迷宫起点位置在(1,1)\n迷宫终点位置在(8,8)\n");
Print(a);
printf("走出迷宫的一条路径为:\n");
Anspath(a,dire);
return 0;
}
迷宫的遍历样例:
{1,1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}