下面是一个用 C++ 实现的迷宫路径查找程序,它使用栈来找到从起点到终点的路径。请根据样例输入输出格式来调整格式。 ```cpp #include <iostream> #include <vector> #include <stack> using namespace std; struct Position { int x, y; }; bool isValid(int x, int y, int m, int n, vector<vector<int>>& maze, vector<vector<bool>>& visited) { return (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0 && !visited[x][y]); } vector<Position> findPath(vector<vector<int>>& maze, int m, int n) { stack<Position> pathStack; vector<vector<bool>> visited(m, vector<bool>(n, false)); // 起点和终点 Position start = {1, 1}; Position end = {m - 2, n - 2}; pathStack.push(start); visited[start.x][start.y] = true; // 方向数组,表示上下左右四个方向的移动 int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 用于存储最终路径 vector<Position> path; while (!pathStack.empty()) { Position current = pathStack.top(); path.push_back(current); // 检查当前是否已经到达终点 if (current.x == end.x && current.y == end.y) { return path; // 返回路径 } bool foundNext = false; // 尝试所有方向 for (int i = 0; i < 4; ++i) { int newX = current.x + directions[i][0]; int newY = current.y + directions[i][1]; if (isValid(newX, newY, m, n, maze, visited)) { pathStack.push({newX, newY}); visited[newX][newY] = true; // 标记为已访问 foundNext = true; break; // 找到下一个位置,结束方向循环 } } // 如果没有找到下一个位置,回退 if (!foundNext) { pathStack.pop(); path.pop_back(); // 从路径中去掉未能到达的节点 } } return {}; // 如果没有找到路径返回空 } 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]; } } vector<Position> path = findPath(maze, m, n); for (const auto& pos : path) { cout << pos.x + 1 << " " << pos.y + 1 << endl; // 输出坐标,行列改为从1开始 } return 0; } ``` 说明: 1. 该程序首先读取迷宫的大小(m 和 n)以及迷宫的结构。 2. `findPath` 函数使用深度优先搜索的方式通过栈来寻找路径。 3. 在找到路径后,程序输出每个坐标的位置(行和列从1开始)。 输入示例: ``` 5 6 1 1 1 1 1 1 1 0 0 1 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 1 ``` 输出示例: ``` 1 1 1 2 2 2 3 2 3 3 3 4 ``` 该程序使用了一个栈来保持路径的探索状态,若无法继续前进,则回溯到上一个节点,保证了路径的唯一性。 [2024-11-03 12:33:51 | AI写代码神器 | 1815点数解答]