【AcWing——宽度优先搜索】AcWing 844. 走迷宫

【AcWing——宽度优先搜索】AcWing 844. 走迷宫_第1张图片
代码:

/**
 * BFS模板套路
 * 1. 将初始状态加入队列queue
 * 2. while queue不空
 * 3. {
 *          3.1 t <- 队头(每次将队头拿出来)
 *          3.2 扩展队头
 *     }
 */

#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef pair<int, int> PII;
const int N = 110;
int m, n;
int g[N][N], d[N][N];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
//PII Prev[N][N];//打印路径使用,记录前一个点是哪个
//stack path;//打印路径使用,用于顺序输出路径

int bfs() {
    memset(d, -1, sizeof(d));
    queue<PII> q;
    d[0][0] = 0;
    q.push({0, 0});
    
    while (!q.empty()) {
        auto t = q.front();
        q.pop();
        for (int i = 0; i < 4; ++i) {
            int x = t.first + dx[i], y = t.second + dy[i];
            if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
                d[x][y] = d[t.first][t.second] + 1;
                q.push({x, y});
                //Prev[x][y] = t;//打印路径使用, 记录x,y这个点是从t这个点过来的
            }
        }
    }
    // // 打印路径使用
    // int x = n - 1, y = m - 1;
    // while (x || y) {
    //     path.push({x, y});
    //     auto t = Prev[x][y];
    //     x = t.first, y = t.second;
    // }
    // path.push({x, y});
    // while (!path.empty()) {
    //     auto node = path.top();
    //     cout << node.first << ' '<< node.second << endl;
    //     path.pop();
    // }
    
    return d[n - 1][m - 1];
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < m; ++j)
            cin >> g[i][j];
            
    cout << bfs() << endl;
    return 0;
}

你可能感兴趣的:(刷题之路)