#include <iostream>
#include <queue>
#include <vector>
#include <utility>
using namespace std;
// 迷宫地图的尺寸
const int ROWS = 5;
const int COLS = 5;
// 定义迷宫地图 1表示路通,0表示障碍
int maze[ROWS][COLS] = {
{1, 0, 1, 1, 1},
{1, 1, 1, 0, 1},
{0, 0, 0, 1, 1},
{1, 0, 1, 1, 0},
{1, 1, 1, 1, 1}
};
// 定义方向数组,表示上下左右四个方向
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { -1, 1, 0, 0 };
// 定义迷宫节点的结构体
struct Node {
int x, y;
Node(int _x, int _y) : x(_x), y(_y) {}
};
// BFS函数
bool BFS(int start_x, int start_y, int dest_x, int dest_y) {
// 定义队列和visited数组
queue<Node> que;
bool visited[ROWS][COLS] = { false };
pair<int, int> parent[ROWS][COLS]; // 用于记录父节点
// 将起点入队,并标记为已访问
que.push(Node(start_x, start_y));
visited[start_x][start_y] = true;
// 开始BFS搜索
while (!que.empty()) {
Node curr = que.front();
que.pop();
// 如果当前节点是终点,则找到了一条路径
if (curr.x == dest_x && curr.y == dest_y) {
// 打印路径
vector<pair<int, int>> path;
pair<int, int> node = { dest_x, dest_y };
while (node.first != start_x || node.second != start_y) {
path.push_back(node);
node = parent[node.first][node.second];
}
path.push_back({ start_x, start_y });
cout << "从起点到终点的路径为:" << endl;
for (int i = path.size() - 1; i >= 0; --i) {
cout << "(" << path[i].first << ", " << path[i].second << ")";
if (i > 0) cout << " -> ";
}
cout << endl;
return true;
}
// 尝试向四个方向搜索
for (int i = 0; i < 4; ++i) {
int nx = curr.x + dx[i];
int ny = curr.y + dy[i];
// 如果新位置在迷宫范围内,且是通路且未被访问过
if (nx >= 0 && nx < ROWS && ny >= 0 && ny < COLS && maze[nx][ny] == 1 && !visited[nx][ny]) {
// 将新位置入队,并标记为已访问
que.push(Node(nx, ny));
visited[nx][ny] = true;
parent[nx][ny] = { curr.x, curr.y }; // 记录父节点
}
}
}
// 如果队列为空,但没有找到路径,返回false
return false;
}
int main() {
// 起点和终点
int start_x = 0, start_y = 0;
int dest_x = 4, dest_y = 4;
// 使用BFS搜索迷宫
if (BFS(start_x, start_y, dest_x, dest_y)) {
cout << "找到了一条从起点到终点的路径!" << endl;
}
else {
cout << "没有找到从起点到终点的路径!" << endl;
}
return 0;
}
用c++下bfs广度优先解决迷宫问题
最新推荐文章于 2024-05-20 18:37:45 发布