走迷宫-栈的使用

#include <stdio.h>

#define MAX_STACK_SIZE 64
#define MAZE_SIZE 7
#define EXIT_ROW 5
#define EXIT_COL 5

struct element
{
   int row;
   int col;
   int dir;
};

struct offset
{
   int vert;
   int hori;
};

char move_str[] = { 'N', 'E', 'S', 'W' };

int maze[MAZE_SIZE][MAZE_SIZE] = {
   1,1,1,1,1,1,1,
   1,0,1,1,1,1,1,
   1,0,0,0,0,1,1,
   1,0,1,1,1,1,1,
   1,0,1,0,0,0,1,
   1,0,0,0,1,0,1,
   1,1,1,1,1,1,1,
};

offset move[] =
{
   {-1,0}, {0,1}, {1,0}, {0,-1} 
};

int mark[MAZE_SIZE][MAZE_SIZE] = {0};
element stack[MAX_STACK_SIZE];
int top = 0;

void Path()
{
   bool found = false;
   int row = 0, col = 0, dir = 0;
   int next_row = 0, next_col = 0, next_dir = 0;

   while( top > -1 && !found )
   {
      row = stack[top].row;
      col = stack[top].col;
      dir = stack[top].dir;

      if( dir > 3 )
      {
         mark[row][col] = 0;

         --top;
         ++stack[top].dir;
         continue;
      }

      next_row = row + move[dir].vert;
      next_col = col + move[dir].hori;

      if( next_row == EXIT_ROW && next_col == EXIT_COL )
      {
         found = true;
         ++top;
         stack[top].row = next_row;
         stack[top].col = next_col;
      }
      else if( !maze[next_row][next_col] && !mark[next_row][next_col] )
      {
         ++top;
         stack[top].row = next_row;
         stack[top].col = next_col;
         stack[top].dir = 0;

         mark[next_row][next_col] = 1;
      }
      else
      {
         ++stack[top].dir;
      }
   }

   if( found )
   {
      for( int i = 0; i < MAZE_SIZE; ++i )
      {
         for( int j = 0; j < MAZE_SIZE; ++j )
         {
            printf("%d ", maze[i][j]);
         }
         printf("\n");
      }
      for( int i = 0; i <= top; ++i )
      {
         printf("(%d, %d, %c)\n", stack[i].row, stack[i].col, move_str[stack[i].dir]);
      }
   }
}

int main(int argc, char **argv)
{
   mark[1][1] = 1;

   stack[0].row = 1;
   stack[0].col = 1;
   stack[0].dir = 0;

   Path();

   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值