迷宫寻找路径算法

博客介绍了一种路径查找算法思想。以当前位置 here、出口位置 dest 和路径栈 path 为基础,通过查找 here 周围的点判断是否有路。若有路,将原位置压入栈并更新 here;若没有则从栈中弹出元素,继续查找。若栈为空则无法找到路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于下面的思想:

here:目前的位置

dest:出口位置

path:路径栈

1:有障碍,0:有路

1、查找here周围的点,看看是否有路

2、如果有,则here=1,将原位置压入栈,再将here指向新的位置

3、没有,path.pop(pop),跳回步骤1。

4、如果没有点,即栈为空,则无法找到路径

void FindRouth()
{
 const int ROW=12;   //该迷宫外面一圈为障碍墙
 const int COL=12;
 const int TOTAL=(ROW-2)*(COL-2);

 int i=0,j=0;

 int maze[ROW][COL];   //迷宫矩阵

//读入迷宫数据,0表示有路,1表示有障碍 

for(i=1;i<ROW-1;i++)
  for(j=1;j<COL-1;j++)
   cin>>maze[i][j];

 //在迷宫外面加一圈围墙,方便比较
 for(i=0;i<ROW;i=i+ROW-1)
  for(j=0;j<COL;j=j+COL-1)
   maze[i][j]=1;

 CStack<CPostion> path(TOTAL-1);  //路径栈
 
 CPostion here; //Current Position
 here.col=2;
 here.row=2;
 CPostion dest; //Out door Position
 dest.col=9;
 dest.row=9; 
 
 

while(!(here==dest))                            //进行比较
 {
  maze[here.row][here.col]=1;  

  if(maze[here.row-1][here.col]==0)
  {
   path.Push(here);
   here.row=here.row-1;
   
   continue;
  }

  if(maze[here.row][here.col-1]==0)
  {
   path.Push(here);
   here.col=here.col-1;
   
   continue;
  }

  if(maze[here.row+1][here.col]==0)
  {
   path.Push(here);
   here.row=here.row+1;
   
   continue;
  }

  if(maze[here.row][here.col+1]==0)
  {
   path.Push(here);
   here.col=here.col+1;
   
   continue;
  }

  if(!path.Pop(here))
  {
   cout<<"there is no route./n";
   return;
  }

  

 }

 cout<<"Success find rout./n";
 while(path.Pop(here))
  cout<<here;


 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值