#include <iostream>
#include <stack>
struct Pos
{
int _row{};
int _col{};
Pos(int row, int col) :_row(row)
, _col(col) {
}
Pos() {
}
};
std::stack<Pos>s;
bool CheckIsAccess(int* a, int row_size, int col_size, Pos cur)
{
//行座標不合法
if (cur._row <0 || cur._row >= row_size){
return false;
}
//列座標不合法
if (cur._col <0 || cur._col>=col_size){
return false;
}
//走過路
if (a[cur._row * col_size + cur._col] >0){
return false;
}
return true;
}
bool check_pos(int* maze, int rows, int cols, Pos entry)
{
s.push(entry);
while (!s.empty()) {
Pos cur = s.top();
Pos next = cur;
//記迷宮的出口僅在下邊緣
if (next._row == rows-1){
return true;
}
//試探上面
next._row--;
if (CheckIsAccess(maze,rows,cols, next)){
maze[cur._row * cols + cur._col] = 2;
s.push(next);
continue;
}
//試探下面
next = cur;
next._row++;
if (CheckIsAccess(maze, rows, cols, next)) {
maze[cur._row * cols + cur._col] = 2;
s.push(next);
continue;
}
//試探左面
next = cur;
next._col--; //列開始減
if (CheckIsAccess(maze, rows, cols, next)) {
maze[cur._row * cols + cur._col] = 2;
s.push(next);
continue;
}
//試探右面
next = cur;
next._col++;
if (CheckIsAccess(maze, rows, cols, next)) {
maze[cur._row * cols + cur._col] = 2;
s.push(next);
continue;
}
//回溯,如果其餘三個方向均不跳出,則表示無通路
maze[cur._row * cols + cur._col] = 3;//將走過的點標記爲3,也可以不標記
//如果此節點無路,就刪除節點
s.pop();
}
return false;
}
int main()
{
int map[10][10] = { 1,1,1,1,1,1,1,1,1,1,
0,0,1,1,1,1,1,1,1,1,
1,0,1,1,1,1,1,1,1,1,
1,0,0,1,1,1,1,1,1,1,
1,1,0,0,0,0,0,1,1,1,
1,1,0,1,1,1,0,1,1,1,
1,1,0,1,1,1,0,1,1,1,
1,1,0,1,1,1,0,1,1,1,
1,1,0,1,1,1,0,0,1,1,
1,1,1,1,1,1,1,0,1,1
};
bool flag = check_pos((int*)map, 10, 10, Pos(1, 0));
}
總結:利用棧的思想,去遍歷每個座標,可以走的座標放入棧中,然後每個取遍歷,直到此座標不能走位置,若不能走,就把此座標刪除掉,然後彈出下一個座標即可