C++ 利用栈求解唯一路径迷宫:从起点 (1,1) 到终点 (m - 2,n - 2)
好的,下面是一个使用栈来解决迷宫问题的 C++ 程序。这个程序会读取迷宫的大小和内容,并找到从起点 (1, 1) 到终点 (m-2, n-2) 的路径。 ```cpp #include <iostream> #include <vector> #include <stack> using namespace std; struct Point { int x, y; }; const int MAX_SIZE = 200; const int dx[4] = {0, 1, 0, -1}; const int dy[4] = {1, 0, -1, 0}; bool isValid(int x, int y, int m, int n, vector<vector<int>>& maze) { return x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0; } void printPath(stack<Point>& path) { while (!path.empty()) { cout << path.top().x + 1 << " " << path.top().y + 1 << endl; path.pop(); } } int main() { int m, n; cin >> m >> n; vector<vector<int>> maze(m, vector<int>(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { cin >> maze[i][j]; } } stack<Point> path; vector<vector<bool>> visited(m, vector<bool>(n, false)); path.push({0, 0}); visited[0][0] = true; while (!path.empty()) { Point current = path.top(); if (current.x == m - 3 && current.y == n - 3) { printPath(path); return 0; } bool found = false; for (int i = 0; i < 4; ++i) { int newX = current.x + dx[i]; int newY = current.y + dy[i]; if (isValid(newX, newY, m, n, maze) && !visited[newX][newY]) { path.push({newX, newY}); visited[newX][newY] = true; found = true; break; } } if (!found) { path.pop(); } } cout << "No path found" << endl; return 0; } ``` 解释 1. Point 结构体:用于存储迷宫中的点。 2. isValid 函数:检查一个点是否在迷宫内且不是障碍物。 3. printPath 函数:打印从栈中弹出的路径。 4. 主函数: - 读取迷宫的大小 `m` 和 `n`。 - 读取迷宫的内容。 - 初始化栈和访问数组。 - 将起点 (0, 0) 压入栈并标记为已访问。 - 使用深度优先搜索(DFS)遍历迷宫,直到找到终点或栈为空。 - 如果找到终点,调用 `printPath` 函数打印路径。 - 如果没有找到路径,输出 "No path found"。 这个程序假设迷宫的最外圈全是障碍物,并且路径是唯一的。希望这能帮到你!如果有任何问题,请随时提问。 ######[AI写代码神器 | 732点数解答 | 2024-11-03 02:34:53]
- MySQL:创建 schooldb 数据库及 teacher、class、course、student 表的完整 SQL 实现(字节豆包 | 312点数解答 | 2024-11-18 14:36:45)302
- Windows环境下C/C++项目开发:完整目录、文件路径及编译脚本设置示例(字节豆包 | 459点数解答 | 2024-11-02 20:38:01)234
- 迷宫探秘:求解扶苏走出数字矩阵迷宫所需步数及循环判定(字节豆包 | 819点数解答 | 2025-11-26 19:27:35)71
- 巧用二分查找:求解塔台超频最小电压实现信号依次传输(字节豆包 | 720点数解答 | 2025-11-26 20:30:18)44
- 用Python轻松将PPT每页转为图片,附代码示例!(阿里通义 | 315点数解答 | 2024-04-23 10:01:04)1350
- Winform开发:含验证与清空功能的注册页面实现(GPT | 5266点数解答 | 2024-06-14 16:04:40)481
- Python 实战:购物折扣计算、列表求和与平方数推导代码全解(字节豆包 | 235点数解答 | 2024-10-28 14:46:54)229
- Python 实现:在 Windows 系统将 PPT 每页轻松转为图片(百度文心 | 692点数解答 | 2024-10-30 18:08:44)377
- Python 实现飞机票款计算:含舱位折扣逻辑与异常处理指南(字节豆包 | 539点数解答 | 2024-12-01 13:10:00)181
- Python 实现:轻松将 PPT 每页转换为图片(DeepSeek | 462点数解答 | 2025-02-17 17:26:45)263
- 多订单窗框切割难题:整数规划求解实现 35000 元利润与 95%利用率(DeepSeek | 1809点数解答 | 2025-05-01 16:57:40)238
- 优化高中英语核心词汇短语HTML页面,这些建议不容错过!(DeepSeek | 217点数解答 | 2025-07-01 23:41:02)188