双端队列BFS:拖拉机

原题链接:https://www.acwing.com/problem/content/2021/
在这里插入图片描述
一个裸的双端队列广搜.

#include <iostream>
#include <cstring>
#include <algorithm>
#include <deque>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;
const int N = 1010;

bool g[N][N], st[N][N];
int dist[N][N];

int bfs(int sx, int sy)
{
    deque<PII> q;
    q.push_back({sx, sy});
    memset(dist, 0x3f, sizeof dist);
    dist[sx][sy] = 0;

    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

    while (q.size())
    {
        auto t = q.front();
        q.pop_front();
		
		// 出队的时候, 判断,这是优化
        if (st[t.x][t.y]) continue;
        st[t.x][t.y] = true;
        
        // 到了 直接退出
        if (!t.x && !t.y) break;

        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)
            {
            	// 是甘草堆的话,w才为1
                int w = 0;
                if (g[x][y]) w = 1;
                if (dist[x][y] > dist[t.x][t.y] + w)
                {
                    dist[x][y] = dist[t.x][t.y] + w;
                    if (!w) q.push_front({x, y});
                    else q.push_back({x, y});
                }
            }
        }
    }
    
    // 开到原点
    return dist[0][0];
}

int main()
{
    int n, sx, sy;
    scanf("%d%d%d", &n, &sx, &sy);
    while (n -- )
    {
        int x, y;
        scanf("%d%d", &x, &y);
        g[x][y] = true;
    }

    printf("%d\n", bfs(sx, sy));

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值