迷宫求解(C语言回溯法)


#include "stdio.h"
struct stack
{
int h;
struct node *top;
};typedef struct stack STK;
struct node
{
int x;
int y;
struct node *next;
};typedef struct node STN;
void dayin(STK *p)
{
STN *q;
q=(STN*)malloc(sizeof(STN));
q->next=p->top;
q=q->next;
while(q->next!=NULL)
{
printf("(%d,%d)",q->x,q->y);
q=q->next;
}
printf("(%d,%d)",q->x,q->y);
}
pop(STK *a,int *b,int *c)
{
STN *o;
o=(STN *)malloc(sizeof(STN));
o->next=a->top;
o=o->next;
*b=o->x;
*c=o->y;
a->top=o->next;

a->h--;
free(o);
}
dayinmigong(int (*u)[5])
{
int a,b;
for(a=0;a<6;a++)
{
for(b=0;b<5;b++)
{
if(u[a][b]==1)printf(" ");
else if(u[a][b]==0)printf("#");
else if(u[a][b])printf("o");
}
printf("\n");
}
}
tot(STK *a,int *b,int *c)
{
STN *o;
o=(STN *)malloc(sizeof(STN));
o->next=a->top;
o=o->next;
*b=o->x;
*c=o->y;
}
tot2(STK *a,int *b,int *c)
{
STN *o;
o=(STN *)malloc(sizeof(STN));
o->next=a->top;
o=o->next;
o=o->next;
*b=o->x;
*c=o->y;
}
main()
{
STK *a;
STN *p;
int a3=0,b3=0;
int a1=99,b1=99,a2=99,b2=99;
int b[6][5]={1,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,0,1,2};
a=(STK*)malloc(sizeof(STK));
a->h=0;
p=(STN*)malloc(sizeof(STN));
a->top=p;
p->next=NULL;
p->x=0;
p->y=0;
a->h++;
dayinmigong(b);
while(b[a3][b3]!=2)
{
if(((b3+1)<5)&&(b[a3][b3+1]==1||b[a3][b3+1]==2)&&((b3+1)!=b2||(a3!=b2))&&((b3+1)!=b1||a3!=a1))
{
b3=b3+1;

p=(STN*)malloc(sizeof(STN));
p->next=a->top;
a->top=p;
p->x=a3;
p->y=b3;
a->h++;
tot2(a,&a2,&b2);
}
else if(((a3+1)<6)&&(b[a3+1][b3]==1||b[a3+1][b3]==2)&&((a3+1)!=a2||(b3!=b2))&&((a3+1)!=a1||(b3!=b1)))
{
a3=a3+1;

p=(STN*)malloc(sizeof(STN));
p->next=a->top;
a->top=p;
p->x=a3;
p->y=b3;
a->h++;
tot2(a,&a2,&b2);
}
else if(((b3-1)>0)&&(b[a3][b3-1]==1||b[a3][b3-1]==2)&&((b3-1)!=b2||(a3!=a2))&&((b3-1)!=b1||(a3!=a1)))
{
b3=b3-1;

p=(STN*)malloc(sizeof(STN));
p->next=a->top;
a->top=p;
p->x=a3;
p->y=b3;
a->h++;
tot2(a,&a2,&b2);
}
else if(((a3-1)>0)&&(b[a3-1][b3]==1||b[a3-1][b3]==2)&&((a3-1)!=a2||(b3!=b2))&&((a3-1)!=a1||(b3!=b1)))
{
a3=a3-1;

p=(STN*)malloc(sizeof(STN));
p->next=a->top;
a->top=p;
p->x=a3;
p->y=b3;
a->h++;
tot2(a,&a2,&b2);
}
else if(b[a3][b3]!=2)
{
pop(a,&a1,&b1);
tot(a,&a3,&b3);
if(a3==0&&b3==0)continue;
tot2(a,&a2,&b2);
}
}
dayin(a);
scanf("%d");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值