迷宫问题:
走过的路设置为2,未走过的路设置0,墙设置为1;
- 解决方法一:栈stack
将每次你所走过的路都push进入栈里面,栈顶元素的坐标就是你所在的位置,取出你所在的位置然后判断当前位置上下左右四个方向是否有通路,如果没有就pop()顶层元素,然后再取出顶层元素(即退一步),然后接着判断其他方向是否有通路,直到你走出边界或者栈为空的时候退出;
缺陷:只找到一条路径就退出,无法判断最短路径是哪一条。
代码如下:
bool CheckPath(const Pos& cur)
{
if(cur._row >= 0 && cur._row < M && cur._col >= 0 && cur._col < N
&& _maze[cur._row][cur._col] == 0)
return true;//这条路可以走
return false;
}
bool GetMazePath(Pos& entry)
{
stack<Pos> paths;
paths.push(entry);
while(!paths.empty())
{
Pos cur = paths.top();
_maze[cur._row][cur._col] = 2;
if(cur._row == M - 1)//已经到达出口
{
return true;
}
Pos next = cur;
//上
next._row -= 1;
if(CheckPath(next))
{
paths.push(next);
continue;
}
next = cur;
//右
next._col += 1;
if(CheckPath(next))
{
paths.push(next);
continue;
}
next = cur;
//下
next._row += 1;
if(CheckPath(next))
{
paths.push(next);
continue;
}
next = cur;
//左
next._col -= 1;
if(CheckPath(next))
{
paths.push(next);
continue;
}
paths.pop();
}
return false;
}
解决方法二:递归
将当前的位置的上下左右状态分别分析,任何一方可以满足条件继续行走即回调当前函数,继续判断,这样一直递归到最后一层退出后,再返回上一次位置继续判断其他方向,保持这样的思路一直进行下去,直到回调到初始位置判断完四个方向都结束后退出。
代码如下:
//递归法
void GetMazePathR(Pos entry)
{
Pos cur = entry;
_maze[entry._row][entry._col] = 2;
if(entry._row == M - 1)
return;
Pos next = cur;
//上
next._row -= 1;
if(CheckPath(next))
{
GetMazePathR(next);
}
next = cur;
//右
next._col += 1;
if(CheckPath(next))
{
GetMazePathR(next);
}
next = cur;
//下
next._row += 1;
if(CheckPath(next))
{
GetMazePathR(next);
}
next = cur;
//左
next._col -= 1;
if(CheckPath(next))
{
GetMazePathR(next);
}
}
求出最短路径:
设置每次走过一条路径都让它是当前路径的值+1,判断条件是下一条路径的值 == 0 时,或者下一条路径的值比当前路径的值大,此路可通过。
代码如下:
bool CheckPath(const Pos& cur, const Pos& pre)
{
if(cur._row >= 0 && cur._row < M && cur._col >= 0 && cur._col < N
&& _maze[cur._row][cur._col] != 1)
{
if(_maze[cur._row][cur._col] == 0)
return true;
else
return _maze[cur._row][cur._col] > _maze[pre._row][pre._col];
}
return false;
}
void GetShortPathR(Pos entry)//递归求最短路径
{
Pos cur = entry;
if(cur._row == M - 1)
return;
Pos next = cur;
//上
next._row -= 1;
if(CheckPath(next,cur))
{
_maze[next._row][next._col] = _maze[cur._row][cur._col] + 1;
GetShortPathR(next);
}
next = cur;
//右
next._col += 1;
if(CheckPath(next,cur))
{
_maze[next._row][next._col] = _maze[cur._row][cur._col] + 1;
GetShortPathR(next);
}
next = cur;
//下
next._row += 1;
if(CheckPath(next,cur))
{
_maze[next._row][next._col] = _maze[cur._row][cur._col] + 1;
GetShortPathR(next);
}
next = cur;
//左
next._col -= 1;
if(CheckPath(next,cur))
{
_maze[next._row][next._col] = _maze[cur._row][cur._col] + 1;
GetShortPathR(next);
}
}