广搜 基础 走迷宫 记录路径

本文介绍了一种使用广度优先搜索(BFS)解决迷宫寻路问题的方法。通过定义方向数组和边界检查函数,确保了算法的有效性和正确性。文章详细展示了如何从起点开始遍历至终点,并记录路径,最后逆向输出整个路径。
###############################
Origin:POJ3984
Type:BFS
##############################
#include <iostream>
#include <cstdio>
#include <stack>
#include <queue>
#include <cstring>
#define N 5
using namespace std;
const int dx[4] = {0, 0, -1, 1};
const int dy[4] = {-1, 1, 0, 0};
int fa[N][N], grid[N][N];
bool vis[N][N];

inline bool inbound (int x, int y)
{
    return (0<=x && x<N && 0<=y && y<N);
}

void bfs(int start, int aim)
{
    int x = start / N, y = start % N;
    fa[x][y] = start;
    vis[x][y] = true;
    queue<int>q;
    q.push(start);
    while (!q.empty()){
        int temp = q.front();
        q.pop();
        x = temp / N, y = temp % N;
        int nx, ny;
        for (int i=0; i<4; i++){
            nx = x + dx[i];
            ny = y + dy[i];
            if (inbound(nx, ny) && !grid[nx][ny] && !vis[nx][ny]){
                fa[nx][ny] = temp;
                int a = nx * N + ny;
                if (a == aim) return ;
                q.push(a);
                vis[nx][ny] = 1;
            }
        }
    }
}

void trace(int aim)
{
    int x =aim/N,y =aim%N,fx,fy;
    stack<int> dir;
    dir.push (aim);
    while (1){
        fx = fa[x][y] / N;
        fy = fa[x][y] % N;
        if (fx == x && fy == y) break;
        dir.push(fa[x][y]);
        x = fx, y = fy;
    }
    while (!dir.empty()){

 printf("(%d, %d)\n",dir.top()/N,dir.top()%N);
     dir.pop();
    }
}
int main()
{
  for(int i=0; i<N; i++)
    for(int j=0; j<N; j++)
        scanf("%d",&grid[i][j]);
    memset(vis, 0, sizeof(vis));
    memset(fa, 0, sizeof(fa));
    bfs(0, N*N-1);
    trace(N*N-1);
    return 0;
}

C++中,使用广度优先索(BFS)算法求解迷宫的最短路径是一种常见且有效的方法。BFS算法的核心思想是从起点开始,逐层扩展索范围,直到找到终点。以下是实现该功能的详细步骤和示例代码: ### 思路 - 首先创建一个空的队列,将起点加入队列。 - 从起点开始访问,然后访问起点周围的相邻点。 - 判断这些相邻点的状态,如果是未访问过且可通行的点,则将该点加入队列。 - 不断重复上述过程,直到访问到终点,此时记录路径即为最短路径;或者直到队列为空,说明没有找到可行路径,输出相应提示信息。 ### 示例代码 ```cpp #include <iostream> #include <queue> #include <vector> using namespace std; // 定义方向数组,分别表示上、下、左、右 const int dx[] = {-1, 1, 0, 0}; const int dy[] = {0, 0, -1, 1}; // 定义点的结构体 struct Point { int x, y; Point(int _x, int _y) : x(_x), y(_y) {} }; // 检查点是否在迷宫范围内且可通行 bool isValid(int x, int y, int rows, int cols, const vector<vector<int>>& maze) { return x >= 0 && x < rows && y >= 0 && y < cols && maze[x][y] == 0; } // BFS函数求解最短路径 int bfs(const vector<vector<int>>& maze, Point start, Point end) { int rows = maze.size(); int cols = maze[0].size(); vector<vector<bool>> visited(rows, vector<bool>(cols, false)); queue<pair<Point, int>> q; q.push({start, 0}); visited[start.x][start.y] = true; while (!q.empty()) { auto [current, dist] = q.front(); q.pop(); if (current.x == end.x && current.y == end.y) { return dist; } for (int i = 0; i < 4; ++i) { int newX = current.x + dx[i]; int newY = current.y + dy[i]; if (isValid(newX, newY, rows, cols, maze) && !visited[newX][newY]) { q.push({Point(newX, newY), dist + 1}); visited[newX][newY] = true; } } } return -1; // 没有找到路径 } int main() { vector<vector<int>> maze = { {0, 1, 0, 0}, {0, 0, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 0} }; Point start(0, 0); Point end(3, 3); int shortestPath = bfs(maze, start, end); if (shortestPath != -1) { cout << "最短路径长度: " << shortestPath << endl; } else { cout << "No Answer." << endl; } return 0; } ``` ### 代码解释 1. **方向数组**:`dx` 和 `dy` 数组用于表示上、下、左、右四个方向的偏移量。 2. **点的结构体**:`Point` 结构体用于表示迷宫中的一个点,包含 `x` 和 `y` 坐标。 3. **检查点的有效性**:`isValid` 函数用于检查一个点是否在迷宫范围内且可通行。 4. **BFS函数**:`bfs` 函数实现了广度优先索的核心逻辑,使用队列存储待访问的点,并使用 `visited` 数组记录已访问的点。 5. **主函数**:在 `main` 函数中,定义了一个迷宫矩阵,设置起点和终点,调用 `bfs` 函数求解最短路径,并输出结果。 ### 复杂度分析 - **时间复杂度**:$O(m * n)$,其中 $m$ 和 $n$ 分别是迷宫的行数和列数。因为每个点最多被访问一次。 - **空间复杂度**:$O(m * n)$,主要用于存储 `visited` 数组和队列。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值