数据结构迷宫源代码

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include

#include

#include

#include

#include

#define OK 1

#define ERROR 0

#define NULL 0

#define OVERFLOW -2

#define STACK_INIT_SIZE 100

#define STACKINCREMENT 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;

//基本操作

int InitStack(SqStack *S)

{

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;

}

//若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR int GetTop(SqStack *S,SElemType *e)

{

if(S->top==S->base) return ERROR;

*e=*(S->top-1);

return OK;

}

int 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;

}

//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR

int Pop(SqStack *S,SElemType *e)

{

if(S->top==S->base) return ERROR;

*e=*--S->top;

return OK;

}

int StackEmpty(SqStack *S)

{

return(S->top==S->base) ;

}

//迷宫程序

typedef struct {

int lie; /*列数*/

int hang; /*行数*/

char a[999][999];

}MazeType; /*迷宫类型*/

/*随机生成迷宫*/

int generatemaze( MazeType *maze)

{

int i,j;

maze->a[0][0]=2;

maze->a[++maze->hang][++maze->lie]=3;

/*设置外墙*/

maze->a[0][maze->lie]='!';

maze->a[maze->hang][0]='!';

for(j=1;jlie;j++)

{maze->a[0][j]='!';maze->a[maze->hang][j]='!';}

for(i=1;ihang;i++)

{maze->a[i][0]='!';maze->a[i][maze->lie]='!';}

srand((unsigned)time( NULL ));

rand();

for(i=1; i hang; i++)

for(j=1;jlie;j++)

{

if (rand()>=RAND_MAX/4) maze->a[i][j] =' '; //' ' 暗示出路

else maze->a[i][j] ='!'; //'!'暗示无出路}

return OK;

}

int Pass(MazeType *maze, PosType curpos ) //判断当前位置可否通过{

if ((curpos.x < 1) || (curpos.x >= maze->lie)) return ERROR;

if ((curpos.y < 1) || (curpos.y >= maze->hang)) return ERROR;

if (maze->a[curpos.y][curpos.x]==' ') return OK;

else return ERROR;

}

int FootPrint(MazeType *maze,PosType curpos) //留下足迹

{

maze->a[curpos.y][curpos.x]='*';

return OK;

}

int MarkPrint(MazeType *maze,PosType curpos) //留下不能通过的标记{

maze->a[curpos.y][curpos.x]='@';

return OK;

}

PosType NextPos(PosType curpos,int di) //返回当前位置的下一位置{

PosType pos=curpos;

switch(di)

{

case 1: //右东

pos.x++;

break;

相关文档
最新文档