AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 校园
  • 应用
  • 文章
    • 题解
    • 分享
    • 问答
  • 吐槽
  • 登录/注册

AcWing 1076. 对搜索顺序的理解    原题链接    简单

作者: 作者的头像   LLYY ,  2022-06-24 08:20:36 ,  所有人可见 ,  阅读 14


0


我们在进行bfs的时候会将所有可能到达的点遍历并入队,但是我们只想要到达终点的那一条路径
易知到达终点的路径只有一条,但是我们每次存的是当前点是由那个点转移过来的,如果正着搜
不能输出从开始到结尾的路径,而且输出的路径也不一定对(到达终点的路径才是唯一的,从起点走的不一定唯一)
所以要倒着搜。


综上所述,倒着搜的原因一共有两点:
1、方便我们正着输出路径
2、从起点开始遍历的路径唯一

#include <iostream>
#include <cstring>
#include <algorithm>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second

const int N = 1010;
int g[N][N];
bool st[N][N];
PII pre[N][N];
int n;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

void bfs(int sx,int sy)
{
    queue<PII>q;
    q.push({sx,sy});
    st[sx][sy] = true;
    while(!q.empty())
    {
        PII 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)continue;
            if(st[x][y])continue;
            if(g[x][y] == 1)continue;
            pre[x][y] = {t.x,t.y};
            q.push({x,y});
            st[x][y] = true;
        }
    }
}

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

    bfs(n - 1,n - 1);

    PII ed = {0,0};
    while(1)
    {
        printf("%d %d\n",ed.x,ed.y);
        if(ed == make_pair(n - 1,n - 1))break;
        ed = pre[ed.x][ed.y];
    }
    return 0;
}

0 评论

你确定删除吗?

© 2018-2022 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息