酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

题目描述 一个5×6的迷宫样例如下: 要求给出从起点(1,1)到终点(3,4)的路径。 为了处理方便,保证最外圈全都为障碍物。 扩展到一般情况,一个m×n的迷宫,要求输出从起点(1,1)到终点(m-2,n-2)的路径。 测试实例保证路径是唯一的。 该题要求自行设计一个栈来做。如果设计的是顺序栈,则保证栈的大小不超过200个元素。 输入 第一行为两个整数m和n,表示m×n的迷宫。 接下来有m行,每行有n个数(n个数之间用空格间隔,值=0表示可以通行,值=1表示为障碍物) 输出 输出从起点到终点的路径,每个坐标占一行,坐标间的行号和列号用一个空格间隔。具体格式可参考样例。 样例输入 复制 5 6 1 1 1 1 1 1 1 0 0 1 0 1 1 1 0 1 0 1 1 0 0 0 0 1 1 1 1 1 1 1 样例输出 复制 1 1 1 2 2 2 3 2 3 3 3 4 用c++

```cpp #include <iostream> #include <stack> using namespace std; struct Point { int x; int y; }; bool isSafe(int x, int y, int m, int n, int maze[][6]) { return (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0); } void findPath(int maze[][6], int m, int n) { stack<Point> s; Point start = {1, 1}; s.push(start); while (!s.empty()) { Point current = s.top(); if (current.x == m - 2 && current.y == n - 2) { break; } maze[current.x][current.y] = 1; if (isSafe(current.x + 1, current.y, m, n, maze)) { Point next = {current.x + 1, current.y}; s.push(next); continue; } if (isSafe(current.x, current.y + 1, m, n, maze)) { Point next = {current.x, current.y + 1}; s.push(next); continue; } if (isSafe(current.x - 1, current.y, m, n, maze)) { Point next = {current.x - 1, current.y}; s.push(next); continue; } if (isSafe(current.x, current.y - 1, m, n, maze)) { Point next = {current.x, current.y - 1}; s.push(next); continue; } s.pop(); } while (!s.empty()) { Point p = s.top(); s.pop(); cout << p.x << " " << p.y << endl; } } int main() { int maze[5][6] = { {1, 1, 1, 1, 1, 1}, {1, 0, 0, 1, 0, 1}, {1, 1, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1} }; findPath(maze, 5, 6); return 0; } ``` [2024-11-03 03:57:12 | AI写代码神器 | 579点数解答]

相关提问