#include<ctype.h>
#include<stdio.h> /* EOF(=^Z或F6),NULL */
#include<stdlib.h> /* atoi() */
#include<io.h> /* eof() */
#include<math.h> /* floor(),ceil(),abs() */
#include<process.h> /* exit() */
/* 函数结果状态代码 */
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
/* #define OVERFLOW -2 因为在math.h中已定义OVERFLOW的值为3,故去掉此行 */
typedef int Status;/* Status是函数的类型,其值是函数结果状态代码,如OK等 */
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define M 10
typedef struct
{
int x;
int y;
}PosType;
typedef struct
{
int ord;
PosType seat;
int di;
}SElemType;
typedef struct
{
SElemType *base; /* 栈底指针 */
SElemType *top; /* 栈顶指针*/
int stacksize; /* 当前分配的存储容量(以元素为单位) */
}SqStack;
Status InitStack(SqStack &S) /* 算法2.3 */
{ /* 操作结果:构造一个空栈 */
S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)
exit(OVERFLOW); /* 存储分配失败 */
S.top=S.base; /* 栈顶与栈底指向一处 */
S.stacksize=STACK_INIT_SIZE; /* 初始存储容量 */
return OK;
}//InitStack
Status Push(SqStack &S,SElemType e)
{
//插入元素e为新的栈顶元素
if(S.top-S.base>=S.stacksize)
{
//栈满,追加存储空间
S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base)exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}//
Status Pop(SqStack &S,SElemType &e)
{
//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
if(S.top==S.base)return ERROR;
e=*--S.top;
return OK;
}//Pop
Status StackEmpty(SqStack S)
{
//若栈为空,则返回TRUE;否则返回FALSE
if(S.top==S.base)return TRUE;
return FALSE;
}//StackEmpty
Status Pass(PosType e,int a[M][M])
{
if(a[e.x][e.y])return TRUE;
return FALSE;
}
void FootPrint(PosType &p,int a[M][M])
{
a[p.x][p.y]=0;
}
PosType NextPos(PosType &m,int n)
{
switch(n)
{
case 1:m.y+=1;break;
case 2:m.x+=1;break;
case 3:m.y-=1;break;
case 4:m.x-=1;break;
default:break;
}
return m;
}
Status MazePath(int maze[M][M],PosType start,PosType end)
{
SqStack S;
int curstep=1;
SElemType e;
PosType curpos=start;
InitStack(S);
do{
if(Pass(curpos,maze))
{
FootPrint(curpos,maze);
e.ord=curstep;
e.seat=curpos;
e.di=1;
Push(S,e);
if(curpos.x==end.x&&curpos.y==end.y)
{
printf("迷宫的其中一条路径为:\n");
while(!StackEmpty(S))
{
Pop(S,e);
printf("(%d,%d)-> ",e.seat.x,e.seat.y);
}
printf("\n");
return TRUE;
}
curpos=NextPos(curpos,1);
curstep++;
}
else
{
if(!StackEmpty(S))
{
Pop(S,e);
while(e.di==4&&!StackEmpty(S))
{
//MarkPrint(e.seat);
Pop(S,e);
}
if(e.di<4)
{
e.di++;
Push(S,e);
curpos=NextPos(e.seat,e.di);
}
}
}
}while(!StackEmpty(S));
printf("此迷宫无可通路径!\n");
return FALSE;
}
int main()
{
int maze[M][M]={{0},{0,1,1,0,1,1,1,0,1,0}
,{0,1,1,0,1,1,1,0,1,0},{0,1,1,1,1,0,0,1,1,0}
,{0,1,0,0,0,1,1,1,1,0},{0,1,1,1,0,1,1,1,1,0}
,{0,1,0,1,1,1,0,1,1,0},{0,1,0,0,0,1,0,0,1,0}
,{0,0,1,1,1,1,1,1,1,0},{0}};//构造迷宫
PosType start,end;
start.x=1;
start.y=1;
end.x=8;
end.y=8;
MazePath(maze,start,end);
return 0;
}
浙公网安备 33010602011771号