老鼠走迷宫

走迷宫算法的伪代码

struct Position
{
  int row,col;
};
bool FindPath()
{
 int maze[m][m];
 //form (1,1) to (m,m)
 path=new Stack<Position>(m*m+1);
 Position offset[4];
  offset[0].row=0;offset[0].col=0; //turn right
  offset[1].row=1;offset[1].col=0; //turn down
  offset[2].row=0;offset[2].col=-1; //turn left
  offset[3].row=-1;offset[3].col=0; //turn up

 //add obstacle around of maze
 for(int i=0;i<=m+1,i++)
 {
  maze[0][i]=maze[m+1][i]=1;  //bottom and top edge
  maze[i][0]=maze[i][m+1]=1;  //left and right edge

 }
 Position here;
 int option=0,lastoption=3; //try to direction 0--3
 here.row=1;
 here.col=1;
//array of maze 
 maze[1][1]=1;
 while(here.row!=m||here.col!=m)
//find next position  
{
while(option<=lastoption)
{
 r=here.row+offset[option].row;
 c=here.col+offset[option].col;
 if (maze[r][c]==0) break;
 option++;  //try next direction
}
if (option<=lastoption)
{
//find a new positon
 path->add(here);
 here.row=r;here.col=c;
 maze[r][c]=1;
 option=0;
}
else
{
 //no new position ,now go back
 if(path->isEmpty()) return false;
 Position next;
 path->Delete(next);//pop up and delete top of stack
 if(next.row=here.row)
  option=2+next.col-here.col; //turn up or down
 else
  option=1+next.row-here.row; //turn left or right
 here=next;  //back to priority position
}
}
 return true;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值