用栈解决迷宫问题

#include<stdio.h>
#include<malloc.h>
#define m 4
#define n 4
#define max 100
int mg[m+2][n+2]=
{
{1,1,1,1,1,1},
{1,0,0,0,1,1},
{1,0,1,0,0,1},
{1,0,0,0,1,1},
{1,1,0,0,0,1},
{1,1,1,1,1,1}
};
typedef struct
{
	int i,j;//行,列
	int di ;
} box;
typedef struct
{
	box data[max];
	int top;
} st;
void initst(st *& s)//初始化 
{
	s=(st*)malloc(sizeof(st));
	s->top=-1;
}
bool push(st *&s,box e)//进栈 
{
	if(s->top==max-1)
		return false;
	s->top++;
	s->data[s->top]=e;
	return true;
}
bool stempty(st *s)//检查空栈 
{
	if(s->top==-1)
		return true;
	return false; 	
}
bool gettop(st *s,box &e)//取栈顶 
{
	if(s->top==-1)
		return false;
	e=s->data[s->top];
	return true;
}
bool pop(st *&s,box &e)//出栈 
{
	if(s->top==-1)
		return false;
	e=s->data[s->top];
	s->top--;
	return true;
}
void destroyst(st *&s)//销毁栈 
{
	free(s);
}
bool mgpath(int xi,int yi,int xe,int ye)
{	
	box path[max],e;
	int i,j,di,il,jl,k;
	bool find;
	st *s;
	initst(s);
	e.i=xi;e.j=yi;e.di=-1;
	mg[xi][yi]=-1;
	push(s,e);
	while(!stempty(s))
	{
		gettop(s,e);
		i=e.i;j=e.j,di=e.di;
		if(i==xe&&j==ye)
		{
			printf("迷宫的一条路径如下: \n");
			k=0;
			while(!stempty(s))
			{
				pop(s,e);
				path[k++]=e;
			}
			while(k>=1)
			{
				k--;
				printf("(%d,%d)",path[k].i,path[k].j);
			}
			printf("\n");
			destroyst(s);
			return true;
		}
		find=false;
		while(di<4&&!find)
		{
			di++;
			switch(di)
			{
				case 0:il=i-1;jl=j;break;
				case 1:il=i;jl=j+1;break;
				case 2:il=i+1;jl=j;break;
				case 3:il=i;jl=j-1;break;
			}		
			if(mg[il][jl]==0)
				find=true;
		}
		if(find)
		{
			s->data[s->top].di=di;
			e.i=il;
			e.j=jl;
			e.di=-1;
			push(s,e);
			mg[il][jl]=-1;
		}
		else
		{
			pop(s,e);
			mg[e.i][e.j]=0;
		}
	}	
	destroyst(s);
	return false;
}
int main() 
{	
	if(!mgpath(1,1,4,4))
	printf("无解"); 
	return 1;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值