分类:
2010-06-13 11:51:00
|
#define MAXSIZE 1024
#define footed -1
#define marked -2
#define East 1
#define South 2
#define West 3
#define North 4
#define True 1
#define False 0
typedef int STATUS;
typedef int DirType;
typedef int BOOL;
typedef struct
{
void *ptr;
int colum;
int row;
}MazeType;
typedef struct
{
int x;
int y;
}PosType;
typedef struct
{
PosType seat;
DirType di;
}StackElement;
typedef struct
{
StackElement *base;
StackElement *top;
int size;
}Stack;
int InitStack(Stack *stp)
{
stp->top = stp->base = (StackElement*)malloc(sizeof(StackElement)*(stp->size));
if(stp->top)return 0;
else printf("Stack Initialized Error!\n");
return 1;
}
int PushStack(Stack *stp,StackElement *sep)
{
if(stp->top-stp->base == stp->size-1)
{
printf("Stack is Full!\n");
return 1;
}
*(stp->top) = *sep;
stp->top++;
return 0;
}
int PopStack(Stack *stp,StackElement *sep)
{
if(stp->base == stp->top)
{
printf("Stack is Empty");
return 1;
}
stp->top--;
*sep = *(stp->top);
return 0;
}
int IsStackEmpty(Stack *stp)
{
if(stp->top == stp->base)return 1;
else return 0;
}
int GetTop(Stack *stp,StackElement *sep)
{
if(stp->top == stp->base)
{
printf("Stack is Empty!\n");
return 1;
}
else *sep = *(stp->top-1);
return 0;
}
void DispPos(PosType pos)
{
printf("Position: %d %d \n",pos.x,pos.y);
}
void DispPath(Stack *st)
{
StackElement *sep;
sep = st->base;
printf("The Path is as following:\n");
while(sep < st->top)
{
printf("(%d,%d)",(sep->seat).x,(sep->seat).y);
if(sep!=st->top-1)printf("-->");
sep++;
}
}
PosType NextPos(PosType pos,DirType dir)
{
switch(dir)
{
case East:
pos.y++;
return pos;
case South:
pos.x++;
return pos;
case West:
pos.y--;
return pos;
case North:
pos.x--;
return pos;
default:
return pos;
}
}
STATUS MazePath(MazeType maze,PosType start,PosType end)
{
int m[maze.row][maze.colum];
int i=0,j=0;
memcpy(m,maze.ptr,sizeof(int)*(maze.row)*(maze.colum));
/*for(i=0;i
for(j=0;j
printf("%d ",m[i][j]);
}*/
printf("\n");
}
Stack st;
st.size = MAXSIZE;
InitStack(&st);
StackElement se;
PosType curpos = start;
DispPos(curpos);
do{
if(m[curpos.x][curpos.y] == 0)
{
m[curpos.x][curpos.y] = footed;
se.seat = curpos;
se.di = East;
PushStack(&st,&se);
if((curpos.x == end.x)&&(curpos.y == end.y))
{
printf("\nSuccessfully arrived at Exit!\n");
DispPath(&st);
return True;
}
curpos = NextPos(curpos,se.di);
DispPos(curpos);
}
else
{
if(!IsStackEmpty(&st))
{
PopStack(&st,&se);
}
while((se.di ==4)&&!IsStackEmpty(&st))
{
m[curpos.x][curpos.y] = marked;
PopStack(&st,&se);
}
if(se.di < 4)
{
se.di++;
PushStack(&st,&se);
curpos = NextPos(se.seat,se.di);
DispPos(curpos);
}
}
}while(!IsStackEmpty(&st));
return False;
}