迷宫

该博客展示了一个用C++实现的迷宫路径搜索程序。程序首先让用户输入迷宫的行列数,随机生成迷宫,接着用户输入起始和终点位置,若位置有效则使用栈结构进行路径搜索,最后输出路径,若位置无效则给出提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

 

转载于:https://www.cnblogs.com/persistence-ok/p/11058078.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值