zoukankan      html  css  js  c++  java
  • 迷宫

    #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;
    }
  • 相关阅读:
    URLEncode解决url中有特殊字符的问题
    监控系统概览
    SpringBoot 上传文件夹
    关于postgresql报 ERROR: XXX does not exist
    postgresql学习
    git学习
    学习博客
    面试准备
    jvm
    线程池面试题
  • 原文地址:https://www.cnblogs.com/persistence-ok/p/11058078.html
Copyright © 2011-2022 走看看