Recursive implementation of the maze problem (sequential stack)

#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 is the direction 
} Stack;                // define the stack type 
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 ;}
    at =StmStack[top].at+ 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;     // Set the direction of the top square of the stack 
        mgpath( x, y,xe,ye);//cmt1
        mg[x][y] = 0 ;     // should smash the block that was passed in the previous step ( cmt1 ) 
top-- ; di ++ ; } }

void main() { mgpath( 1 , 1 , 8 , 8 ); }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975793&siteId=291194637