搜索迷宫路径(stack)

// 寻找从位置(1,1)到出口(m,m)的路径
int **maze, m;
Stack<Position> *path;
bool FindPath()
{
 path=new Stack<Position>(m*m-1);
 Position offset[4];
 offset[0].row=0; offset[0].col=1; // right
 offset[1].row=1; offset[1].col=0; // down
 offset[2].row=0; offset[2].col=-1; // left
 offset[3].row=-1; offset[3].col=0; //up
 // 在迷宫周围增加一圈障碍物
 for(int i=0;i<m+1;i++)
 {
  maze[0][i]=maze[m+1][i]=1;
  maze[i][0]=maze[i][m+1]=1;
 }
 Position here;
 here.row=1;
 here.col=1;
 // 阻止返回入口
 maze[1][1]=1;
 int option=0;
 int LastOption=3;
 //寻找一条路径
 while(here.row!=m || here.col!=m)
 {
  // 寻找并移动到一个相邻位置
  int r, c;
  while(option<=LastOption)
  {
   r=here.row+offset[option].row;
   c=here.col+offset[option].col;
   if(maze[r][c]==0)
    break;
   option++;
  }
  // 找到一个相邻位置?
  if(option<=LastOption)
  {
   //移动到maze[r][c]
   path->Add(here);
   here.row=r;
   here.col=c;
   // 设置障碍物以阻止再次访问
   maze[r][c]=1;
   option=0;
  }
  else
  {
   // 没有可用的位置,回溯
   if(path->IsEmpty())
    return false;
   Position next;
   path->Delete(next);
   if(next.row==here.row)
    option=2+next.col-here.col;
   else
    option=3+next.row-here.row;
   here=next;
  }
 }
 return true;
}

Ref:<<数据结构,算法与应用>>P180~186

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值