#include<iostream>
#include<vector>
using namespace std;
class MyWay
{
public:
struct coor//保存数组下标
{
int x, y;
bool operator==(coor &other)
{
return (this->x == other.x&&this->y == other.y);
}
friend ostream&operator<<(ostream&os, coor&other)
{
os << '[' << other.x << ',' << other.y << ']';
return os;
}
};
void DS()//深度寻路
{
if (way.empty())return;//栈为空,直接返回
if (end == way.back())return;//到达终点,直接返回
coor next = way.back();
//右
if (next.y + 1 < col&&map[next.x][next.y + 1] == 0)//可以走
{
way.push_back({ next.x, next.y + 1 });//入栈
map[next.x][next.y + 1] = 2;//走过的路
DS();//继续递归遍历
}
//下
if (next.x + 1 < row&&map[next.x + 1][next.y] ==0 )
{
way.push_back({next.x+1,next.y});
map[next.x + 1][next.y] = 2;
DS();
}
//左
if (next.y- 1<col&&map[next.x][next.y-1] == 0)//可以走
{
way.push_back({ next.x, next.y - 1 });//入栈
map[next.x][next.y - 1] = 2;//走过的路
DS();//继续递归遍历
}
//上
if (next.x - 1<row&&map[next.x - 1][next.y ]== 0)
{
way.push_back({ next.x - 1, next.y });
map[next.x - 1][next.y] = 2;
DS();
}
if (way.back() == end)return;//如果都没有找到退出
way.pop_back();//当前位置出栈 退回之前的位置
}
void findWay(coor begin,coor end,int *arr,int row,int col)
{
this->begin = begin;
this->end = end;
this->row = row;
this->col = col;
map.resize(row);//分配长
for (int i = 0; i < row;++i)
{
map[i].resize(col);//分配对应长的宽
for (int j = 0; j < col; ++j)
{
map[i][j] = arr[i*col + j];
}
way.push_back(begin);//起点进栈
map[begin.x][end.y] = 2;
DS();//开始找路
}
}
void putWay()//打印
{
vector<coor>::iterator it;
for (it = way.begin(); it != way.end(); ++it)
{
cout << *it << '\t';
}
}
private:
vector<coor> way;
vector<vector<int>>map;//地图:动态二维数组
int row, col;//数组的长和宽
coor begin, end;//起点和终点
//辅助数组
};
int main()
{
int map[5][5] = //地图
{
0, 0, 1, 1, 1,
1, 0, 1, 0, 1,
1, 0, 1, 0, 1,
1, 0, 0, 0, 0,
1, 1, 1, 1, 0
};
MyWay ways;
ways.findWay({ 0, 0 }, { 4, 4 }, &map[0][0], 5, 5);
ways.putWay();
cin.get();
return 0;
}