该代码使用vs2019编译,分为1个头文件和两个cpp文件
//头文件声明(Stack.h)
#ifndef STACK_H
#define STACK_H
typedef struct{
//x, y方向的增量
int incX, incY;
}Direction;
typedef struct {
int x, y;//当前访问的迷宫格子的纵横坐标
int di;//当前方向
}Box;
class Stack {
private:
Box* data;//属性:线性表
int size;//属性:堆栈的实际大小
int top; //属性:栈顶
public:
Stack(); //构造函数
Stack(int s); //有参构造函数
~Stack(); //析构函数
void push(Box ch); //成员函数:入栈
Box pop(); //成员函数:出栈并返回栈顶元素
Box getTop(); //成员函数:获得栈顶元素(不出栈)
bool isEmpty(); //成员函数:栈是否为空
bool isFull(); //成员函数:栈是否为满
void setNull(); //设置栈为空
};
#endif // ! STACK_H
//类函数实现(Stack.cpp)
#include <iostream>
#include "stack.h"
using namespace std;
#define MAX_SIZE 100
Stack::Stack() {
size = MAX_SIZE;
top = -1;
data = new Box[MAX_SIZE];//缺省构造函数分配最大内存空间
}
Stack::Stack(int s) {
size = s;
top = -1;
data = new Box[size];//根据指定的大小分配栈的内存空间
}
Stack::~Stack() {
delete[] data;//内存回收
}
void Stack::push(Box ch) {
if (!isFull()) {
data[++top] = ch;
}
}
Box Stack::pop() {
if (!isEmpty()) {
return data[top--];;
}
}
Box Stack::getTop() {
if (!isEmpty()) {
return data[top];
}
}
bool Stack::isEmpty() {
if (top == -1) {
return true;
}
else {
return false;
}
}
bool Stack::isFull() {
if (top == size - 1) {
return true;
}
else {
return false;
}
}
void Stack::setNull() {
top = -1;
}
//主函数实现(main.cpp)
#include "stack.h"
#include <iostream>
using namespace std;
#define M 8
#define N 8
int maze[10][10] = {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},//1
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},//2
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},//3
{1, 0, 0, 0, 0, 1, 1, 0, 0, 1},//4
{1, 0, 1, 1, 1, 0, 0, 0, 0, 1},//5
{1, 0, 0, 0, 1, 0, 0, 0, 0, 1},//6
{1, 0, 1, 0, 0, 0, 1, 0, 0, 1},//7
{1, 0, 1, 1, 1, 0, 1, 1, 0, 1},//8
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1},//9
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},//10
};
Direction direct[4] = { {0,1},{1,0},{0,-1},{-1,0} };
bool findPath(int maze[M + 2][N + 2], Direction direct[], Stack& s) {
Box temp;
int x, y, di;//迷宫格子当前处理单元的纵横坐标和方向
int line, col;//迷宫数组下一单元的行坐标和列坐标
maze[1][1] = -1;//-1表示走过的格子
temp = { 1, 1, -1 };
s.push(temp);//先压栈
while (!s.isEmpty()) {//栈不为空
temp = s.pop();//尝试四个方向都不行需要出栈
x = temp.x; y = temp.y; di = temp.di + 1;
while (di < 4) {//方向未尝试完
line = x + direct[di].incX;
col = y + direct[di].incY;
if (maze[line][col] == 0) {
temp = { x, y, di };
s.push(temp);//压栈
x = line; y = col; maze[line][col] = -1;
if (x == M && y == N) {
temp = { M, N, di };
s.push(temp);
return true;//迷宫有路
}
else {
di = 0;
}
}
else di++;
}
}
return false;//迷宫没有路
}
int main() {
Stack s1(20);
Box temp;
if (findPath(maze, direct, s1)) {
cout << "迷宫有路" << endl;
while (!s1.isEmpty())
{
temp = s1.pop();
cout << temp.x << "," << temp.y << endl;
}
}
else {
cout << "迷宫没有路" << endl;
}
s1.~Stack();//删除栈
}
本文是在学习b站懒猫的视频后写出,详细思路看一看懒猫老师视频懒猫老师-数据结构-(8)栈的应用:迷宫问题(DFS,非递归)_哔哩哔哩_bilibili