zoukankan      html  css  js  c++  java
  • 求解迷宫最短路

    ## 有缺陷,待改进,等我再学学::>_<::

    #include <iostream>
    #include <string>
    #include <queue>
    #include <stack>
    using namespace std;
    
    int maze[105][105];
    bool mark[105][105];
    int step1[105][105];
    int step2[105][105];
    
    struct PosInfor
    {
        int px,py;
        PosInfor(int x=0,int y=0):px(x),py(y) {}
    };
    
    struct Offsets
    {
        int dx,dy;
        Offsets(int x=0,int y=0):dx(x),dy(y) {}
    };
    
    Offsets guide[4]= {{0,1},{1,0},{0,-1},{-1,0}};
    
    int main()
    {
        int N;
        cin>>N;
        for(int i=0; i<N; i++)
        {
            for(int j=0; j<N; j++)
            {
                cin>>maze[i][j];
                if(i==0 || i==N-1 || j==0 || j==N-1)
                    mark[i][j]=1;
            }
        }
    
        mark[1][1]=1;
    
        PosInfor po;
        queue<PosInfor> q;
        q.push(PosInfor(1,1));
    
        int nx,ny,f=0;
    
        while(!q.empty())
        {
            po = q.front();
            q.pop();
            for(int i=0; i<4; i++)
            {
                nx = po.px + guide[i].dx;
                ny = po.py + guide[i].dy;
                if(maze[nx][ny]==1 || mark[nx][ny]==1)
                    continue;
                if(nx==N-2 && ny==N-2)
                {
                    f=1;
                }
                q.push(PosInfor(nx,ny));
                step1[nx][ny]=po.px;
                step2[nx][ny]=po.py;
                mark[nx][ny]=1;
            }
            if(f==1)
                break;
        }
        stack<PosInfor> result;
        if(f==1)
        {
            int a,b,x,y;
            x=step1[N-2][N-2]; //8
            y=step2[N-2][N-2];  //7
           // cout<<"("<<N-2<<","<<N-2<<")"<<endl;
            result.push(PosInfor(N-2,N-2));
            while(a&&b)  //判断ab之前要初始化
            {
                //cout<<"("<<x<<","<<y<<")"<<endl;
                result.push(PosInfor(x,y));
                a=step1[x][y]; //8
                b=step2[x][y];
                x=a;
                y=b;
            }
            while(!result.empty())
            {
               po=result.top();
                cout<<"("<<po.px<<","<<po.py<<")";
                result.pop();
            }
    
        }
        else
            cout<<"NO";
    
        return 0;
    }
  • 相关阅读:
    Visual C#使用DirectX实现视频播放
    windows WMIC命令大全
    WMI 无法监视时必须要尝试的手段 winmgmt /resyncperf
    DirectX技术实现视频会议中的音频通信
    c++引用
    c++模板详解
    四元数
    static_cast 和 dynamic_cast
    C++堆和栈详解(转)
    设计模式六大设计原则
  • 原文地址:https://www.cnblogs.com/syzyaa/p/13818070.html
Copyright © 2011-2022 走看看