1076. 迷宫问题 bfs

#include <iostream>
#include <cstring>
#include <queue>
#include <stack>

#define x first
#define y second

using namespace std;

typedef pair<int ,int> PII;

const int N = 1010;

PII pre[N][N];//存储当前位置的前驱
int g[N][N];
bool st[N][N];//表示当前位置的状态,若已用则为true,反之为false.
int n;
int dx[4] = {-1,1,0,0}, dy[4] = {0,0,-1,1};//当前位置的上、下、左、右偏移量

void bfs(){
    queue <PII> q;

    q.push({0, 0});

    while(q.size()){
        auto t = q.front();
        q.pop();

        for(int i = 0; i < 4; i ++){
            int x = t.x + dx[i], y = t.y + dy[i];
            if(x >= 0 && x < n && y >= 0 && y < n && g[x][y] == 0 && st[x][y] == false){
                st[x][y] = true;
                pre[x][y] = t;//存储一下当前合理位置的前驱,即该位置由哪个位置引入
                q.push({x, y});
            }
        }
    }
}

int main(){
    cin >> n;

    for(int i = 0; i < n; i ++){
        for(int j = 0; j < n; j ++){
            cin >> g[i][j];
        }
    }

    bfs();


    stack<PII> s;
    int x = n - 1, y = n - 1;
    while(x || y){
        s.push({x, y});
        auto t = pre[x][y];
        x = t.x, y = t.y;
    }
    s.push({0, 0});

    //打印方案
    while(s.size()){
        PII t = s.top(); s.pop();
        cout << t.x << ' ' << t.y << endl;
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值