C++ 利用栈算法求解 5×6 迷宫从起点到终点的唯一路径
```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; } ``` ######[AI写代码神器 | 579点数解答 | 2024-11-03 03:57:12]
- MySQL:创建 schooldb 数据库及 teacher、class、course、student 表的完整 SQL 实现(字节豆包 | 312点数解答 | 2024-11-18 14:36:45)319
- Windows环境下C/C++项目开发:完整目录、文件路径及编译脚本设置示例(字节豆包 | 459点数解答 | 2024-11-02 20:38:01)252
- 迷宫探秘:求解扶苏走出数字矩阵迷宫所需步数及循环判定(字节豆包 | 819点数解答 | 2025-11-26 19:27:35)86
- 用Python轻松将PPT每页转为图片,附代码示例!(阿里通义 | 315点数解答 | 2024-04-23 10:01:04)1392
- Winform开发:含验证与清空功能的注册页面实现(GPT | 5266点数解答 | 2024-06-14 16:04:40)500
- Python 实战:购物折扣计算、列表求和与平方数推导代码全解(字节豆包 | 235点数解答 | 2024-10-28 14:46:54)243
- Python 实现:在 Windows 系统将 PPT 每页轻松转为图片(百度文心 | 692点数解答 | 2024-10-30 18:08:44)390
- Python 实现飞机票款计算:含舱位折扣逻辑与异常处理指南(字节豆包 | 539点数解答 | 2024-12-01 13:10:00)192
- Python 实现:轻松将 PPT 每页转换为图片(DeepSeek | 462点数解答 | 2025-02-17 17:26:45)288
- 多订单窗框切割难题:整数规划求解实现 35000 元利润与 95%利用率(DeepSeek | 1809点数解答 | 2025-05-01 16:57:40)250
- 优化高中英语核心词汇短语HTML页面,这些建议不容错过!(DeepSeek | 217点数解答 | 2025-07-01 23:41:02)207
- Python切片操作巧解经典算法:二维数组90°旋转(阿里通义 | 205点数解答 | 2023-10-31 11:05:29)351