#include<iostream>
#include<malloc.h>
#define maxsize 20
#define M 8
#define N 8
using namespace std;
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,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
//用栈进行走迷宫问题
typedef struct{
int i,j;
int di;
}Box;
typedef struct{
Box data[maxsize];
int top;
}Stack;
//初始化一个栈
void init(Stack *&s){
s=(Stack*)malloc(sizeof(Stack));
s-> top =-1;
}
//取栈顶元素
bool gettop(Stack *s,Box &e){
if(s->top!=-1){
e.i=s-> data [s->top].i;
e.j=s-> data [s->top].j;
e.di=s->data [s->top].di;
return true;
}
else return false;
}
//弹出栈顶元素
bool pop(Stack *&s,Box &e){
if(s->top!=-1){
e.i=s-> data [s->top].i;
e.j=s-> data [s->top].j;
e.di=s->data [s->top].di;
s->top--;
return true;
}
else return false;
}
//判断栈是否为空
bool empty(Stack *s){
return (s->top==-1);
}
//进栈操作
bool push(Stack *&s,Box e){
if(s->top==maxsize-1) {
return false;
}
else {
s->top++;
s-> data [s->top].i=e.i ;
s-> data [s->top].j=e.j ;
s-> data [s->top].di=e.di ;
return true;
}
}
//摧毁一个栈
void destory(Stack *&s){
free(s);
}
bool mgpath(int x1,int y1,int x2,int y2){
Box path[maxsize],e;
Stack *s;
init(s);
int i,j,di,i1,j1,k;
bool find;
e.i=x1;e.j=y1;e.di=-1;
push(s,e);
mg[x1][y1]=-1;
while(!empty(s)){
gettop(s,e);
i=e.i;j=e.j;di=e.di ;
if(i==x2&&j==y2){
cout<<"一条迷宫的路径如下:"<<endl;
k=0;
while(!empty(s)){
pop(s,e);
path[k++]=e;
}
while(k>=1){
k--;
printf("\t(%d,%d)",path[k].i,path[k].j);
if((k+2)%5==0){
cout<<endl;
}
}
destory(s);
return true;
}
find=false;
while(di<4&& !find){
di++;
switch(di){
case 0: i1=i-1;j1=j;break;
case 1: i1=i;j1=j+1;break;
case 2: i1=i+1;j1=j;break;
case 3: i1=i;j1=j-1;break;
}
if(mg[i1][j1]==0) find=true;
}
if(find){
s->data[s->top].di=di;
e.i=i1;e.j=j1;e.di=-1;
push(s,e);
mg[i1][j1]=-1;
}
else {
pop(s,e);
mg[e.i][e.j]=0;
}
}
destory(s);
return false;
}
int main(){
if(!mgpath(1,1,M,N)){
cout<<"没有路径"<<endl;
}
return 1;
}
用栈进行走迷宫问题 (2021-11-06)
最新推荐文章于 2023-11-22 23:21:08 发布