用栈求解迷宫,由于基础不牢,编得很乱,出不了正确结果,望高人指教。。。谢谢!!!
# include <stdio.h># include <malloc.h>
typedef struct
{
int x,y;
int flag;
}postype,posch[20][20];
typedef struct
{
int ord;
postype seat;
int di;
}selemtype;
typedef struct
{
posch a;
int m;
int n;
int t;
postype start,end;
}mazetype;
typedef struct sqstack
{
selemtype *top;
selemtype *base;
int stacksize;
}sqstack;
sqstack initstack(sqstack S)
{
S.base=(selemtype *)malloc(100*sizeof(selemtype));
S.top=S.base;
S.stacksize=100;
return S;
}
sqstack push(sqstack S,selemtype *e)
{
*S.top=*e;
S.top++;
return S;
}
sqstack pop(sqstack S,selemtype *e)
{
S.top--;
*e=*S.top;
return S;
}
stackempty(sqstack S)
{
if(S.base==S.top)
return 1;
else
return 0;
}
postype nextpos(postype Q,int n)
{
switch(n)
{
case 1: Q.y++;break;
case 2: Q.x++;break;
case 3: Q.y--;break;
case 4: Q.x--;break;
}
return Q;
}
mazetype creat(mazetype M)
{
int i,j,p,q;
scanf("%d%d%d",&M.m,&M.n,&M.t);
for(i=0;i<=M.m;i++)
for(j=0;j<=M.n;j++)
{
M.a[i][j].flag=0;
}
for(i=0;i<M.t;i++)
{
scanf("%d%d",&p,&q);
scanf("%d",&M.a[p][q].flag);
}
return M;
}
void main()
{
sqstack S;
mazetype maze;
int curstep=1;
selemtype *e;
postype curpos;
e=(selemtype *)malloc(sizeof(selemtype));
maze=creat(maze);
scanf("%d%d%d%d%d%d",&maze.start.x,&maze.start.y,&maze.start.flag,&maze.end.x,&maze.end.y,&maze.end.flag);
S=initstack(S);
curpos=maze.start;
do
{
if(maze.a[curpos.x][curpos.y].flag)
{
curpos.flag=0;
e->ord=curstep;
e->seat=curpos;
e->di=1;
S=push(S,e);
if(curpos.x==maze.end.x&&curpos.y==maze.end.y)
break;
curpos=nextpos(curpos,1);
curstep++;
}
else
{
if(!stackempty(S))
{
S=pop(S,e);
while(e->di==4&&!stackempty(S))
{
e->seat.flag=0;
S=pop(S,e);
}
if(e->di<4)
{
e->di++;
S=push(S,e);
curpos=nextpos(e->seat,e->di);
}
}
}
}while(!stackempty(S));
while(!stackempty(S))
{
S=pop(S,e);
printf("(%d,%d)",e->seat.x,e->seat.y);
}
}