zoukankan      html  css  js  c++  java
  • 递归实现迷宫问题(顺序栈)

    #include <iostream.h>
    #define MaxSize 100
    #define M 8
    #define N 8
    int mg[M+2][N+2]=
    {
        {1,1,1,1,1,1,1,1,1,1},
        {1,0,0,1,1,0,0,1,0,1},
        {1,1,0,1,0,1,0,1,0,1},
        {1,0,0,0,0,0,0,0,1,1},
        {1,0,1,1,1,0,1,0,0,1},
        {1,0,1,0,1,1,0,1,0,1},
        {1,0,1,0,0,0,1,1,0,1},
        {1,0,1,1,1,0,1,1,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,1,1,1,1,1,1,1,1,1}
    };
    
    typedef struct
    {   int i,j,di;//di为方向
    } Stack;               //定义栈类型
    Stack StmStack[100];
    int top=-1;
    bool safe(int xi,int yi)
    {
        if(xi>8||yi>8||xi<1||yi<1||mg[xi][yi]==1||mg[xi][yi]==-1) return 0;
        return 1;
    }
    void disp(int top)
    {int i=0;
    while (i<=top) {
        cout<<StmStack[i].i<<','<<StmStack[i].j<<endl;
        i++;}
    }
    void mgpath(int xi,int yi,int xe,int ye)
    {
        int di,x=xi,y=yi;
        top++;
        StmStack[top].i=x;StmStack[top].j=y;StmStack[top].di=-1;mg[x][y]=-1;
        if(x==xe && y==ye) {
            cout<<"find it!"<<endl;
            disp(top);return ;}
        di=StmStack[top].di+1;
        
        while(di<4)
        {   
            switch (di)
            {
            case 0:y=yi+1; x=xi;break ;
            case 1:x=xi+1; y=yi;break;
            case 2:x=xi-1; y=yi;break;
            case 3:y=yi-1;x=xi; break;
            } 
            if(!safe(x,y)) {di++;continue;}
            StmStack[top].di=di;    //设置栈顶方块的方向
            mgpath( x, y,xe,ye);//cmt1
            mg[x][y]=0;    //应该抺掉上一步(cmt1)走过的方块 
    top--; di++; } }

    void main() { mgpath(1,1,8,8); }
  • 相关阅读:
    存储型 XSS 原理复现
    反射型 XSS 原理复现
    HTTP 简易理解
    Markdown 流程图语法
    Dirsearch 快速开始
    sqlmap 快速开始
    SQL 注入原理
    XSS 原理
    51nod 1835 完全图
    11.5 AM 请求
  • 原文地址:https://www.cnblogs.com/ewitt/p/8960763.html
Copyright © 2011-2022 走看看