数据结构——迷宫求解

效果如下:



源代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define M 100
#define ERROR 0 
#define OK 1
char a[10][10]={{'*','*','*','*','*','*','*','*','*','*'},
{'*','0','0','*','0','0','0','*','0','*'},
{'*','0','0','*','0','0','0','*','0','*'},
{'*','0','0','0','0','*','*','0','0','*'},
{'*','0','*','*','*','0','0','0','0','*'},
{'*','0','0','0','*','0','0','0','0','*'},
{'*','0','*','0','0','0','*','0','0','*'},
{'*','0','*','*','*','0','*','*','0','*'},
{'*','*','0','0','0','0','0','0','0','*'},
{'*','*','*','*','*','*','*','*','*','*'},};
typedef struct
{
int row;
int col;
}postype;
typedef struct
{
int ord;
postype seat;
int di;
}Chartype;
typedef struct
{
Chartype *base;
Chartype *top;
int stacksize;
}sqstack;
int Initstack(sqstack &s)
{
   s.base = (Chartype*)malloc(M * sizeof(Chartype));
   if(!s.base)return ERROR;
   s.top = s.base;
   s.stacksize = M;
   return OK;
}
int Pass(postype curpos)
{
if(a[curpos.row][curpos.col]=='0')
return 1;
   else 
return 0;
}
void Footprint(postype curpos)
{


  a[curpos.row][curpos.col]='->';
}
int push(sqstack &s, Chartype  &e)
{
   *s.top++ = e;
   return OK;
}
int pop(sqstack &s, Chartype &e)
{
   if(s.top == s.base)
   return ERROR;
   e = * --s.top;
   return OK;
}
postype nextpos(postype curpos,int x)
{
if(x==1)
    curpos.col=curpos.col+1;
else if(x==2)
curpos.row= curpos.row+1;
else if(x==3)
curpos.col= curpos.col-1;
else
curpos.row= curpos.row-1;
return curpos;
}
void markprint(postype e)
{
a[e.row][e.col]='&';
}
int stackempty(sqstack s)
{
    if(s.base == s.top)
     return 1;
   else
     return 0;
}
int main()
{
int i, j, curstep = 1,x=0;
    postype start = {1,1}, end = {8, 8}, curpos;
sqstack s;
Chartype e;
    Initstack(s);
curpos=start;
printf("...........迷宫求解..............\n");
printf("还没有走的迷宫\n");
 for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
printf("%c ", a[i][j]);
}printf("\n");
}
 do
 {
 if(x=Pass(curpos))
 {
 Footprint(curpos);
 e.ord=curstep;
 e.seat=curpos;
 e.di=1;
 push(s,e);
 if(curpos.row==end.row&&curpos.col==end.col)
 { 
 printf("迷宫已经走完了!\n");
 break;
 }
           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("一共走了%d步\n",curstep);
  printf("已经走完的迷宫:\n");
  for(i=0;i<10;i++)
  {
  for(j=0;j<10;j++)
  {
  printf("%c ",a[i][j]);
  }
  printf("\n");
  }
  return 0;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值