利用c++语言和堆栈实现迷宫寻址的代码 同时迷宫地图从文件中读取
时间: 2023-12-10 14:39:14 浏览: 28
以下是利用C++语言和堆栈实现迷宫寻址的代码,并且可以从文件中读取迷宫地图:
```c++
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
const int MAX_ROW = 10;
const int MAX_COL = 10;
struct Point {
int row, col;
};
Point operator+(const Point& lhs, const Point& rhs) {
return{ lhs.row + rhs.row, lhs.col + rhs.col };
}
bool operator==(const Point& lhs, const Point& rhs) {
return lhs.row == rhs.row && lhs.col == rhs.col;
}
bool operator!=(const Point& lhs, const Point& rhs) {
return !(lhs == rhs);
}
char maze[MAX_ROW][MAX_COL+1];
bool visited[MAX_ROW][MAX_COL];
Point directions[4] = {
{-1, 0}, // 上
{0, 1}, // 右
{1, 0}, // 下
{0, -1} // 左
};
void print_maze() {
for (int i = 0; i < MAX_ROW; ++i) {
cout << maze[i] << endl;
}
cout << endl;
}
void read_maze() {
ifstream fin("maze.txt");
if (!fin.is_open()) {
cerr << "Failed to open file." << endl;
return;
}
for (int i = 0; i < MAX_ROW; ++i) {
fin.getline(maze[i], MAX_COL+1);
}
fin.close();
}
void mark_path(const Point& p) {
maze[p.row][p.col] = '.';
}
bool is_valid(const Point& p) {
if (p.row < 0 || p.col < 0 || p.row >= MAX_ROW || p.col >= MAX_COL) {
return false;
}
if (maze[p.row][p.col] == '*' || visited[p.row][p.col]) {
return false;
}
return true;
}
void depth_first_search(Point start, Point end) {
stack<Point> s;
s.push(start);
while (!s.empty()) {
Point current = s.top();
s.pop();
if (current == end) {
mark_path(current);
print_maze();
return;
}
visited[current.row][current.col] = true;
for (const auto& direction : directions) {
Point neighbor = current + direction;
if (is_valid(neighbor)) {
s.push(neighbor);
}
}
}
cout << "No path found." << endl;
}
int main() {
read_maze();
Point start = { 0, 0 };
Point end = { MAX_ROW-1, MAX_COL-1 };
print_maze();
depth_first_search(start, end);
return 0;
}
```
上述代码中,我们定义了一个 `Point` 结构体,表示迷宫中的一个点。我们实现了 `operator+`、`operator==` 和 `operator!=` 来支持点的加法、相等和不等判断。
`maze` 数组存储了迷宫地图,`visited` 数组表示每个位置是否已经访问过。`directions` 数组存储了四个方向,用于遍历邻居节点。
`read_maze` 函数从文件中读取迷宫地图,`print_maze` 函数输出迷宫地图。`mark_path` 函数用于标记路径上的位置,`is_valid` 函数用于判断一个位置是否合法。
`depth_first_search` 函数实现了深度优先搜索算法。我们使用一个栈来存储待访问的节点。每次从栈中取出一个节点,如果该节点是目标节点,则标记路径并输出迷宫地图。否则,将该节点标记为已访问,并遍历所有邻居节点,将未访问过的、合法的邻居节点加入到栈中。如果栈为空,则表示无法找到路径。
在 `main` 函数中,我们读取迷宫地图,设置起点和终点,输出迷宫地图并执行深度优先搜索算法。