数据结构——迷宫求解问题

        迷宫求解代码如下:


#define stack_init_size 200

#define overflow 0
#define ok 1
#define error 0

#include<stdio.h>
#include<malloc.h>

typedef int Status;

typedef struct{
int x;
int y;
}PosType;

int mg[10][10];
int zx[5],zy[5];

typedef struct {
int ord;
PosType seat;
int di;
}SElemType;

typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

SqStack s;

//构造一个空栈
Status InitStack(SqStack &s){
s.base =(SElemType *)malloc(stack_init_size * sizeof(SElemType));
if(!s.base) return overflow;
s.top=s.base;
s.stacksize=stack_init_size;
return ok;
}

//当前块可否通过
Status Pass(PosType e){
 int i,j;
i=e.x;
j=e.y;
if (mg[i][j]==0)  //0时可以通过
  return ok;
return overflow;
}

//留下足迹
Status FootPrint(PosType e){
 int i,j;
i=e.x;
j=e.y;
mg[i][j]=-1;
return ok;}

//压入栈
Status Push(SqStack &s,SElemType e){
*s.top++=e;
return ok;}

//出栈
Status Pop(SqStack &s,SElemType &e){
if(s.top==s.base)
return error;
e=*--s.top;
return ok;
}

//下一步
PosType NextPos(PosType &e,int di){
e.x=e.x+zx[di];
e.y=e.y+zy[di];
return e;
}

//是否空栈
Status StackEmpty(SqStack s){
if (s.top==s.base)
  return ok;
return overflow;
 }

//留下不能通过的足迹
Status MarkPrint(PosType e){
 int i,j;
i=e.x;
j=e.y;
mg[i][j]=1;
return ok;}

//迷宫函数
Status MazePath(int mg,PosType start,PosType end,SqStack &s){
 PosType curpos;
 SElemType e;
 int curstep;

curpos=start;
curstep=1;
do{
 if(Pass(curpos)){
FootPrint(curpos);
e.ord=curstep;
e.seat.x=curpos.x;
e.seat.y=curpos.y;
e.di=1;
Push(s,e);
if((curpos.x==end.x)&&(curpos.y==end.y))
return ok;
curpos=NextPos(curpos,1);
curstep++;}//if
 else{
  if(!StackEmpty(s)){
Pop(s,e);
while(e.di==4 && !StackEmpty(s)){
MarkPrint(e.seat);
Pop(s,e);
}//while
if(e.di<4){
e.di++;
Push(s,e);
curpos=NextPos(e.seat,e.di);
}//if
  }//if
 }//else
}while(!StackEmpty(s));
return error;}//MazePath

//主函数
void main(){
PosType start,end;
int i,j,x,y;
SElemType e;
for(i=1;i<=8;i++)
  for(j=1;j<=8;j++)
   scanf("%d",&mg[i][j]);
  for(i=0;i<=9;i++){
  mg[i][0]=1;mg[i][9]=1;}
  for(j=0;j<=9;j++){
  mg[0][j]=1;mg[9][j]=1;}
InitStack(s);
start.x=1;
start.y=1;
end.x=8;
end.y=8;
zx[1]=0;
zy[1]=1;
zx[2]=1;
zy[2]=0;
zx[3]=0;
zy[3]=-1;
zx[4]=-1;
zy[4]=0;
MazePath(**mg,start,end,s);
while(!StackEmpty(s))
{Pop(s,e);
x=e.seat.x;
y=e.seat.y;
printf(("%d,%d"),x,y);}

}
        此程序在vc++上一运行成功,是一个8*8的迷宫,最外层还有一圈墙,迷宫道路人为输入。

转载于:https://www.cnblogs.com/liunao/archive/2005/11/19/280243.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值