#include <iostream>
#include <stack>
//基于深度优先搜索 回溯 栈
using namespace std;
struct position
{
int row;
int col;
position()
{
row=col=0;
}
};
bool findPath()
{
stack<position> path;
position offset[4]; //0 1 2 3 右下左上
offset[0].row = 0; offset[0].col = 1;
offset[1].row = 1; offset[1].col = 0;
offset[2].row = 0; offset[0].col =-1;
offset[3].row = -1; offset[0].col = 0;
for(int i=0;i<=size+1;i++) //边界铺围墙 所以不用判断边界还是中间部分 每个位置都有四个方向 省去了代码
{
maze[0][i] = maze[size+1][i] = 1;
maze[i][0] = maze[i][size+1] = 1;
}
position here;
here.row = 1; //入口
here.col = 1;
maze[1][1] = 1; //防止回到入口
int option = 0; //下一步
while(here.col!=size && here.row!=size) //如果没到出口 #注意 是正方形的出口 x y 相同
{
int r,c;
while(option<=3) //选择方向
{
//下一步要走的坐标
r = here.row + offset[option].row;
c = here.col + offset[option].col;
if(maze[r][c] == 0) break; //如果可行
option++; //不可行继续判断 知道判断完所有方向
}
//相邻的一步是否找到
if(option<=3) //找到了
{
path.push(here); //入栈
here.col = c;
here.row = r; //更新现在的坐标
maze[r][c] = 1; //防止回去
option = 0;
}
else
{
//没有路可以走
if(path.empty()) //如果栈空
return false;
position next = path.top(); //回去上一步
path.pop(); //出栈
if(next.row == here.row) //如果两个位置是左右位置 只需要
option= 1 + next.col-here.col; //如果是左右 那么只需判断原来位置的上下
else
option = 2 + next.row-here.row; //原来位置的上下 只需要左右
}
}
return true;
}
注意:上面代码有些变量没有定义 (参考c++算法与数据结构)这里找的不是最短路径 仅仅可以找到通路
maze二维数组是路的标志 1不通 0通 刚开始外面一圈都是1意思是围墙 每次行走都要标记 防止回去
option代表方向
offset代表每个方向的移动
判断位置可行就下一步