用c++下bfs广度优先解决迷宫问题

#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;
}

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值