#include <iostream>
#include <vector>
#include <stack>
#include <utility>
using namespace std;
const int ROWS = 5;
const int COLS = 5;
// 定义迷宫的地图
int maze[ROWS][COLS] = {
{1, 1, 1, 1, 1},
{0, 0, 1, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 0, 0, 0},
{1, 1, 1, 1, 1}
};
// 定义方向数组,用于向上、下、左、右四个方向移动
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
// 定义表示迷宫节点的结构体
struct Node {
int x, y;
Node(int _x, int _y) : x(_x), y(_y) {}
};
// 定义DFS函数,寻找从起点到终点的路径
bool DFS(int start_x, int start_y, int dest_x, int dest_y, vector<pair<int, int>>& path, vector<vector<bool>>& visited) {
// 如果当前节点是终点,则找到了一条路径
if (start_x == dest_x && start_y == dest_y) {
path.push_back({ start_x, start_y });
return true;
}
// 标记当前节点为已访问
visited[start_x][start_y] = true;
path.push_back({ start_x, start_y });
// 尝试向四个方向搜索
for (int i = 0; i < 4; ++i) {
int nx = start_x + dx[i];
int ny = start_y + dy[i];
// 如果新位置在迷宫范围内,且是通路且未被访问过
if (nx >= 0 && nx < ROWS && ny >= 0 && ny < COLS && maze[nx][ny] == 1 && !visited[nx][ny]) {
// 递归搜索下一个节点
if (DFS(nx, ny, dest_x, dest_y, path, visited)) {
return true;
}
}
}
// 如果当前节点无法到达终点,则将当前节点出栈
path.pop_back();
return false;
}
int main() {
int start_x = 0, start_y = 0;
int dest_x = 4, dest_y = 4;
// 定义路径向量和visited数组
vector<pair<int, int>> path;
vector<vector<bool>> visited(ROWS, vector<bool>(COLS, false));
// 调用DFS函数寻找路径
if (DFS(start_x, start_y, dest_x, dest_y, path, visited)) {
cout << "从起点到终点存在路径" << endl;
cout << "路径为:";
for (const auto& p : path) {
cout << "(" << p.first << ", " << p.second << ") ";
}
cout << endl;
}
else {
cout << "从起点到终点不存在路径" << endl;
}
return 0;
}
用c++下dfs深度优先解决迷宫问题
于 2024-03-19 12:51:08 首次发布