#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define TRUE 1
#define ERROR 0
#define FALSE 0
typedef int Status;
typedef struct {
int x; //行
int y; //列
}PosType; //坐标
typedef struct {
int ord; //路径的“序号”
PosType seat; //坐标位置
int di; //下一个通道方向
}MElemType;//每个元素包含的信息有位置,方向,序号
typedef struct node{
MElemType data;
struct node *next;
}MNode, *MStack;
typedef int MazeType[10][10];
Status InitStack(MStack *S)
{
*S=NULL;
return OK;
}
Status Push(MStack *S,MElemType e)
{
MNode *p,*q;
p=*S;
q=(MNode *)malloc(sizeof(MNode));
q->next=p;
q->data=e;
*S=q;
return OK;
}
Status Pop(MStack *S,MElemType *e)
{
MNode *p;
if((*S)==NULL)
return ERROR;
*e=(*S)->data;
p=*S;
*S=(*S)->next;
free(p);
return OK;
}
Status StackEmpty(MStack S)
{
if(S==NULL)
return TRUE;
return FALSE;
}
void PrintStack(MStack S)
{
MNode *p;
if(S==NULL)
printf("The stack is empty!\n");
p=S;
while(p)
{
printf("%d (%d,%d)\n",p->data.di,p->data.seat.x,p->data.seat.y);
p=p->next;
}
}
Status Pass(PosType current,MazeType maze)
{
if(current.x>=0&¤t.x<=9&¤t.y>=0&¤t.y<=9&&maze[current.x][current.y]==0)
return TRUE;
return FALSE;
}
void FootPrint(PosType current,MazeType maze)
{
maze[current.x][current.y] = 2;
}
void MarkPrint(PosType e,MazeType maze)
{
maze[e.x][e.y] = -1;
}
PosType NextPos(PosType seat,int di)
{
PosType e;
if(di==1)
{
e.x = seat.x;
e.y = seat.y+1;
}
if(di==2)
{
e.x = seat.x+1;
e.y = seat.y;
}
if(di==3)
{
e.x = seat.x;
e.y = seat.y-1;
}
if(di==4)
{
e.x = seat.x-1;
e.y = seat.y;
}
// printf("222222222\n");
return e;
}
Status MazePath(MazeType maze,PosType Begin,PosType End)
{
int i,j;
MStack S;
int curstep = 1;
MElemType e;
PosType current =Begin ;
printf("1111111111\n");
InitStack(&S);
/*current.x= Begin.x;
current.y = Begin.y;*/
do{
if(Pass(current,maze))
{
FootPrint(current,maze);
e.di = 1;
e.ord = curstep;
e.seat = current;
Push(&S,e);
if(current.x== End.x&¤t.y==End.y)
{
for(i=0;i<=9;i++)
{
for(j=0;j<10;j++)
{
printf("%3d ",maze[i][j]);
}
printf("\n");
}
PrintStack(S);
return OK;
}
current = NextPos(current ,1);
//current.y++;
curstep++;
}
else
{
if(!StackEmpty(S))
{
Pop(&S,&e);
while(e.di==4&&!StackEmpty(S)){
MarkPrint(e.seat,maze);
Pop(&S,&e);
}
if(e.di<4)
{
e.di++;
Push(&S,e);
/*current.x = e.seat.x;
current.y = e.seat.y;*/
current = NextPos(e.seat,e.di);
}
}
}
}while(!StackEmpty(S));
for(i=0;i<=9;i++)
{
for(j=0;j<10;j++)
{
printf("%3d ",maze[i][j]);
}
printf("\n");
}
return FALSE;
}
int main()
{
MazeType M ={
{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}
};
PosType Begin,End;
Begin.x = 1;
Begin.y = 1;
End.x=8;
End.y = 8;
if(MazePath(M,Begin,End)==OK)
printf("能到达!\n");
else
printf("不能到达!\n");
return 0;
}