数据结构--迷宫问题

来源:互联网 发布:网络推广模式 编辑:程序博客网 时间:2024/05/21 08:04
/* 
设计一个迷宫求解程序,要求如下:
以M × N表示长方阵表示迷宫,求出一条从入口到出口的通路,或得出没有通路的结论。
能任意设定的迷宫
*/


#include <iostream>
using namespace std;


#define MaxSize 1000


int mg[MaxSize][MaxSize];


typedef struct{
int i;                   //当前方块的行号 
int j;                   //当前方块的列号 
int di;                  // di是下一个可走的相邻方块的方位号 
}Box;


typedef struct{
Box data[MaxSize];
int top;                 //栈顶指针 
}StType;                     //定义顺序栈类型 


bool mgpath(int xi,int yi,int xe,int ye){     //求解路径(xi,yi)->(xe,ye) 
int i,j,k,di,find;
StType st;
st.top=-1;
st.top++;
st.data[st.top].i=xi;   st.data[st.top].j=yi;
st.data[st.top].di=-1;  mg[xi][yi]=-1;
while(st.top>-1){
i=st.data[st.top].i;   j=st.data[st.top].j;
di=st.data[st.top].di;

if(i=xe && j==ye){
cout<<"迷宫路径如下:"<<endl;
for(k=0;k<=st.top;k++){
cout<<"\t("<<st.data[k].i<<","<<st.data[k].j<<")";
if((k+1) % 5 == 0)
cout<<endl;
}
cout<<endl;
return true;
}

find = 0;

while(di<4&&find==0){
di++;
switch(di){
case 0:i=st.data[st.top].i-1;j=st.data[st.top].j;break;
case 1:i=st.data[st.top].i;j=st.data[st.top].j+1;break;
case 2:i=st.data[st.top].i+1;j=st.data[st.top].j;break;
case 3:i=st.data[st.top].i;j=st.data[st.top].j-1;break;
}
if(mg[i][j]==0)  find=1;
}

if(find==1){
st.data[st.top].di=di;
st.top++;
st.data[st.top].i=i; st.data[st.top].j=j;
st.data[st.top].di=-1;
mg[i][j]=-1;
}
else{
mg[st.data[st.top].i][st.data[st.top].j]=0;
st.top--;
}
}
return false;



int main(){
int M,N;
int a,b;
int c,d;
cout<<"设置迷宫大小:\t"; 
cin>>M>>N;        //设置迷宫大小
for(int i=0;i<M+2;i++)
for(int j=0;j<N+2;j++)
cin>>mg[i][j];
cout<<"设置入口值\t";
cin>>a>>b;
cout<<"设置出口值\t";
cin>>c>>d;
if(!mgpath(a,b,c,d))
cout<<"该迷宫问题无解"<<endl;
return 0; 
}
0 0
原创粉丝点击