栈的应用实例3—迷宫求解问题

栈的应用实例3—迷宫求解问题

  • 用栈求解迷宫问题:
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

#define STACK_INIT_SIZE 1000   //栈的初始化容量 
#define STACK_INC_SIZE 100	  //栈的分配增量 
#define M  8   //迷宫的行 
#define N  8   //迷宫的列 

//迷宫中点的位序 
typedef struct MAGE{
	int i;
	int j;
}Mage;

typedef Mage elemType; 	 //栈中存放的是Mage类型的数据 
	
Mage a[STACK_INIT_SIZE]; //点的位序结构体数组 

int mg[M+2][N+2]={
	 {1,1,1,1,1,1,1,1,1,1},
	 {1,0,0,1,0,0,0,1,0,1},
	 {1,0,0,1,0,0,0,1,0,1},
	 {1,0,0,0,0,1,1,0,0,1},
	 {1,0,1,1,1,0,0,0,0,1},
	 {1,0,0,0,1,0,0,0,0,1},
	 {1,0,1,0,0,0,1,0,0,1},
	 {1,0,1,1,1,0,1,1,1,1},
	 {1,1,0,0,0,0,0,0,0,1},
	 {1,1,1,1,1,1,1,1,1,1},
};

//栈的数据结构
typedef struct{
	elemType* base;  //栈底指针 
	elemType* top;	 //栈顶指针 
	int stackSize;	 //当前已分配的栈总存储空间 
}SqStack; 

void initStack(SqStack& S);  			  //构造空栈并初始化 
void pushStack(SqStack& S,elemType data); //数据元素进栈
void popStack(SqStack& S);  		   	  //数据元素出栈 
void findWay(int i1,int j1,int i2,int j2,SqStack& S); //迷宫求解

void initStack(SqStack& S)
{ 
	S.base=(elemType*)malloc(STACK_INIT_SIZE * sizeof(elemType));
	if(!S.base)  exit(1);
	S.top=S.base;
	S.stackSize=STACK_INIT_SIZE;  
} 

void pushStack(SqStack& S,elemType data)
{
	if(S.top-S.base>=S.stackSize) //栈满,扩充容量 
	{
		S.base=(elemType*)realloc(S.base,(S.stackSize+STACK_INC_SIZE) * sizeof(elemType));
		if(!S.base)  exit(1);
		S.top=S.base+S.stackSize; //栈顶改变
		S.stackSize+=STACK_INC_SIZE;
	}
	*S.top=data;
	cout<<"进栈:"<<"("<<(*S.top).i<<","<<(*S.top).j<<")";
	S.top++;
	cout<<endl;
}

void popStack(SqStack& S)
{
	if(S.top!=S.base)
	{
		cout<<"出栈:"<<"("<<(*(S.top-1)).i<<","<<(*(S.top-1)).j<<")";
		S.top--;
	} 
	cout<<endl;
}

void printStack(SqStack& S)
{
	cout<<"栈中的内容为:"<<endl;
	for(elemType* i=S.base;i<S.top;i++)
	{
		int j=0;
		cout<<"("<<(*(i+j)).i<<","<<(*(i+j)).j<<")--->"<<"  ";  
		j++;
	}
}

//求解迷宫 
void findWay(int i1,int j1,int i2,int j2,SqStack& S)
{
	a[0].i=i1;
	a[0].j=j1;	
	for(int m=1;;m++)
	{
		if(((*(S.top-1)).i==i2)&&((*(S.top-1)).j==j2))
		{
			printStack(S);
			cout<<"到达终点!!"; 
			exit(0);
		}
		if(mg[i1-1][j1]==0)  //上 
		{
			a[m].i=i1-1;
			a[m].j=j1;
			pushStack(S,a[m]);
			mg[i1-1][j1]=-1;
			findWay(a[m].i,a[m].j,i2,j2,S);
		}
		else if(mg[i1][j1+1]==0)  //右 
		{
			a[m].i=i1;
			a[m].j=j1+1;
			pushStack(S,a[m]);
			mg[i1][j1+1]=-1;
			findWay(a[m].i,a[m].j,i2,j2,S);
		}
		else if(mg[i1+1][j1]==0)  //下 
		{
			a[m].i=i1+1;
			a[m].j=j1;
			pushStack(S,a[m]);
			mg[i1+1][j1]=-1;
			findWay(a[m].i,a[m].j,i2,j2,S);
		}
		else if(mg[i1][j1-1]==0)  //左 
		{
			a[m].i=i1;
			a[m].j=j1-1;
			pushStack(S,a[m]);
			mg[i1][j1-1]=-1;
			findWay(a[m].i,a[m].j,i2,j2,S);
		}
		else
		{
			mg[a[m].i][a[m].j]=-1;
			popStack(S);
			findWay((*(S.top-1)).i,(*(S.top-1)).j,i2,j2,S);
		}
	}
}

int main()
{
	SqStack S;     //定义栈S 
	initStack(S);  //初始化空栈S
	findWay(1,1,8,8,S); 
	return 0;
}

运行结果:
/

发布了77 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42932834/article/details/91348197