走迷宫算法的伪代码
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;
}