码迷,mamicode.com
首页 > 其他好文 > 详细

递归实现迷宫问题(顺序栈)

时间:2018-04-27 12:19:18      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:struct   bre   color   #define   define   顺序   cas   --   code   

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

 

递归实现迷宫问题(顺序栈)

标签:struct   bre   color   #define   define   顺序   cas   --   code   

原文地址:https://www.cnblogs.com/ewitt/p/8960763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!