迷宫问题/栈实现
#include"stdio.h"
#include"stdlib.h"
#define STACK_INIT_SIZE 50
#define STACK_INCREMENT 10
#define ERROR 0
#define OK 1
#define FALSE 0
#define TRUE 1
#define OVERFLOW -2
#define status int
#define ElemType Point
int a[7][9]={{1,1,0,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,1},
{1,0,1,1,1,1,1,1,1},
{1,0,1,0,0,0,1,0,1},
{1,0,1,0,1,0,1,0,1},
{1,0,0,0,1,0,0,0,1},
{1,1,1,1,1,1,1,0,1}};
bool trace[7][9]={0};
typedef struct {
int x;
int y;
int d;
}Point;
typedef struct{
int m;
int n;
}position;
position Move[4]={{1,0},{0,1},{-1,0},{0,-1}};
typedef struct{
Point *base;
Point *top;
int stacksize;
}Stack;
status Initstack(Stack &s){
s.base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!s.base) exit(OVERFLOW);
s.top=s.base;
s.stacksize=STACK_INIT_SIZE;
return OK;
}
status Clearstack(Stack s){
s.top=s.base;
}
status Emptystack(Stack s){
if(s.top==s.base) return TRUE;
return FALSE;
}
status Gettop(Stack s,ElemType &e){
if(Emptystack(s)) return ERROR;
e=*(s.top-1);
return OK;
}
status Destroystack(Stack &s){
free(s.base);
return OK;
}
status Pushstack(Stack &s,ElemType &e){
if(s.top-s.base>=s.stacksize){
s.base=(ElemType *)realloc(s.base,(STACK_INIT_SIZE+STACK_INCREMENT)*sizeof(ElemType));
if(!s.base) exit(OVERFLOW);
s.top=s.base+s.stacksize;
s.stacksize+=STACK_INCREMENT;
}
*s.top++=e;
return OK;
}
status Popstack(Stack &s,ElemType &e){
if(Emptystack(s)) return ERROR;
e=*(--s.top);
return OK;
}
int main(){
Point start={6,7,0},end={0,2,0};
int d=end.d,i=end.x,j=end.y;
Point p,q;
Stack s;
Initstack(s);
do{
if(!a[i+Move[d].m][j+Move[d].n]&&!trace[i+Move[d].m][j+Move[d].n]){
p.x=i;p.y=j;p.d=d;
Pushstack(s,p);
Gettop(s,p);
printf("(%d,%d,%d)\n",p.x,p.y,p.d);
trace[i][j]=1;
i+=Move[d].m;j+=Move[d].n;
if(i==start.x&&j==start.y) {
p.x=i;p.y=j;p.d=d;
Pushstack(s,p);break;
}
d=0;
}
else{
d++;
}
while(d>=4){
Gettop(s,p);
printf("(%d,%d,%d)\n",p.x,p.y,p.d);
Popstack(s,p);
d=p.d;
i=p.x;
j=p.y;
d++;
}
}while(!Emptystack(s));
printf("maze as follows:\n\n");
for(i=0;i<7;i++){
for(j=0;j<9;j++)
printf("%d ",a[i][j]);
printf("\n");
}
printf("-----------------------------------\n");
printf("start point: (%d,%d)\n",start.x,start.y);
printf("end point: (%d,%d)\n",end.x,end.y);
printf("-----------------------------------\n");
if(Emptystack(s)) printf("No way!\n");
else while(!Emptystack(s)) {
Gettop(s,p);
printf("-> (%d,%d) ",p.x,p.y);
Popstack(s,p);
}
printf("\n--------------------------------------------------------------------------------");
Destroystack(s);
}