C++ 迷宫求解算法:非递归栈实现,寻找所有路径和最短路径
#include
struct Node {
int x;
int y;
Node(int i, int j) : x(i), y(j) {}
};
bool isValid(int x, int y, int m, int n, vector<vector
void findPath(int m, int n, vector<vector
stack<Node> s;
s.push(Node(startX, startY));
maze[startX][startY] = 1; // 标记已访问过的点
while (!s.empty()) {
Node curr = s.top();
int x = curr.x;
int y = curr.y;
if (x == endX && y == endY) {
cout << '(' << x << ',' << y << ')'; // 输出最终路径
return;
}
bool found = false;
// 向下走
if (isValid(x + 1, y, m, n, maze)) {
s.push(Node(x + 1, y));
maze[x + 1][y] = 1;
found = true;
}
// 向右走
else if (isValid(x, y + 1, m, n, maze)) {
s.push(Node(x, y + 1));
maze[x][y + 1] = 1;
found = true;
}
// 向上走
else if (isValid(x - 1, y, m, n, maze)) {
s.push(Node(x - 1, y));
maze[x - 1][y] = 1;
found = true;
}
// 向左走
else if (isValid(x, y - 1, m, n, maze)) {
s.push(Node(x, y - 1));
maze[x][y - 1] = 1;
found = true;
}
if (!found) {
// 说明当前节点无法继续向下探索
s.pop();
}
}
cout << "No path found." << endl;
}
int main() {
int m = 5;
int n = 5;
vector<vector
findPath(m, n, maze);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/qBfp 著作权归作者所有。请勿转载和采集!