// 寻找从位置(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