迷宫

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <stack>
using namespace std;
typedef struct node
 {
    int row;
    int col;
    int direction;
 };
stack<node> path;

void ok()
{
    srand(time(NULL));
    int i,j,m,n;

    cout<<"输入行列数"<<endl;
    cin>>m>>n;
    int a[m][n]={{0}};
    for (i=0;i<m;i++)
    {
        a[i][0]=1;
        a[i][n-1]=1;
        for (j=1;j<n-1;j++)
        {
            if(i==0||i==m-1){
                a[i][j]=1;}
            else{
            int rate = rand()%10+1;
            if(rate<=2){a[i][j]=1;}
            else{a[i][j]=0;}
            }
        }
    }
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
            cout<<a[i][j]<<"  ";
        cout<<endl;
    }
int x,y,k,d;
cout<<"请输入起始位置"<<endl;
cin>>x>>y;
cout<<"请输入终点位置"<<endl;
cin>>k>>d;
if(a[x][y]==0&&a[k][d]==0)
{
   while(x<=m||y<=n)
   {
       node s;bool success=false;
       if(a[x][y+1]==0){s.row=x;s.col=y;s.direction=6;a[x][y]=3;path.push(s);y=y+1;success=true;}
        else if(a[x+1][y]==0){s.row=x;s.col=y;s.direction=7;a[x][y]=3;path.push(s);x=x+1;success=true;}
        else if(a[x][y-1]==0){s.row=x;s.col=y;s.direction=8;a[x][y]=3;path.push(s);y=y-1;success=true;}
        else if(a[x-1][y]==0){s.row=x;s.col=y;s.direction=5;a[x][y]=3;path.push(s);x=x-1;success=true;}
     if(!success){
     node fit =path.top();
     a[fit.row][fit.col]=9;
     x=fit.row;y=fit.col;
     }
   }
}
else{cout<<"出口或入口无效"<<endl;}
while(!path.empty())
{
    node c=path.top();
    cout<<"("<<c.row<<","<<c.col<<","<<c.direction<<")"<<"  ";
    path.pop();
}
}


int main()
{
    ok();
    return 0;
}

 

posted @ 2019-06-20 12:49  晨曦yd  阅读(130)  评论(0编辑  收藏  举报