数据结构4——迷宫问题(栈)
利用栈的思想,解决迷宫问题:
我们通过一个二维数组定义一个迷宫
int migong[7][7]={
{1,1,1,1,1,1,1},
{1,0,0,1,0,0,1},
{1,0,0,1,0,1,1},
{1,0,0,0,0,0,1},
{1,0,1,0,1,0,1},
{1,0,1,0,1,0,1},
{1,1,1,1,1,1,1}
};
以下解决迷宫问题
#include<stdio.h>
#include<stdlib.h>
typedef int elmtype;
typedef struct{
elmtype row;
elmtype column;
elmtype derection;
}Lu;
typedef struct{
Lu date[50];
int top;
}SequenStack;
SequenStack *init();
int Push(SequenStack *S,Lu t);
int Pop(SequenStack *S,Lu *t);
int Get(SequenStack *S,Lu *t);
int main(){
int migong[7][7]={
{1,1,1,1,1,1,1},
{1,0,0,1,0,0,1},
{1,0,0,1,0,1,1},
{1,0,0,0,0,0,1},
{1,0,1,0,1,0,1},
{1,0,1,0,1,0,1},
{1,1,1,1,1,1,1}
};
SequenStack *s;
Lu temp;
Lu tryPath;
Lu t;
int x,y,d,i,j,time,yet=0;
s=init();
temp.row=1;
temp.column=1;
temp.derection=0;
Push(s,temp);
while(s->top!=-1)
{
Get(s,&temp);
x=temp.row;
y=temp.column;
d=temp.derection+1;
time=0;
while(d<=4)
{
if(d==1){i=x;j=y+1;}
if(d==2){i=x+1;j=y;}
if(d==3){i=x;j=y-1;}
if(d==4){i=x-1;j=y;}
if(migong[i][j]==0)
{
if(time==0)
{
Pop(s,&tryPath);
tryPath.derection=d;
Push(s,tryPath);
time++;
}
temp.row=i;
temp.column=j;
temp.derection=1;
Push(s,temp);
x=i;
y=j;
migong[x][y]=-1;
if(x==5&&y==5)
yet=1;
else
d=1;
}
else
{
d++;
time=0;
}
if(d==5&&s->top!=-1)
{
Pop(s,&temp);
migong[x][y]='X';
}
if(s->top==-1)
yet=0;
}
int i=0;
if(yet==1){
printf("该迷宫的路径为\n");
while(i<s->top){
printf("%d,%d->",s->date[i].row,s->date[i].column);
i++;
}
if(i==s->top)
{
printf("%d,%d",s->date[i].row,s->date[i].column);
}
}return 1;
}
}
SequenStack *init(){
SequenStack *S;
S=(SequenStack*)malloc(sizeof(SequenStack));
S->top=-1;
return S;
}
int Push(SequenStack *S,Lu t){
S->top++;
S->date[S->top]=t;
return 1;
}
int Pop(SequenStack *S,Lu *t){
S->top--;
*t=S->date[S->top+1];
return 1;
}
int Get(SequenStack *S,Lu *t){
*t=S->date[S->top];
}