AcWing第23场周赛 4004. 传送阵 题解

4004. 传送阵 - AcWing题库高质量的算法题库https://www.acwing.com/problem/content/description/4007/

输入样例1:

5
1 1
5 5
00001
11111
00111
00110
00110

输出样例1:

10

输入样例2:

3
1 3
3 1
010
101
010

输出样例2:

8

输入样例3:

1
1 1
1 1
0

输出样例3:

0

 思路:

先从起点走, 把途径的点都放入队列p[0]中,

若是走到了终点则直接返回并输出"0", 

若无法走到, 则从终点走, 并把途径的点都放入队列p[1]中

最终在两个队列中取出最大传送门开销

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int N = 51;
typedef pair<int, int> PII;
vector<PII> p[2]; // 若不连通, p[0] p[1] 分别表示起点/终点所能到达的区域

int n;
char g[N][N];
bool st0[N][N], st1[N][N];// 标记是否走过
int x0,y0,x1,y1;

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};//方向偏移量

void dfs(int x, int y, bool st[][N], int type)// type: 0-从起点开始, 1-从终点开始
{
    st[x][y] = true;
    if(!type && x==x1 && y==y1) return; //一点小优化, 若从起点走到了终点,则直接返回
    
    p[type].push_back({x,y});
    for(int i = 0; i < 4; i ++)
    {
        int nx = x+dx[i], ny = y+dy[i];
        //判断边界与合理性
        if(nx>=0 && nx<n && ny>=0 && ny<n && !st[nx][ny] && g[nx][ny]=='0')
            dfs(nx, ny, st, type);
    }
}

int main()
{
    cin >> n;
    cin >> x0 >> y0 >> x1 >> y1;

    //题意横纵坐标均从1开始,都减一映射到g[][]
    x0--, y0--;
    x1--, y1--;
    for(int i = 0; i < n; i ++) scanf("%s", g[i]);
    
    dfs(x0, y0, st0, 0);
    int res = 0x3f3f3f3f;
    if(st0[x1][y1]){
        cout << '0';
    }else{
        dfs(x1, y1, st1, 1);
        for(auto t0 : p[0]){
            for(auto t1: p[1]){
                int px = t0.first-t1.first, py = t0.second-t1.second;
                res = min(res, px*px+py*py);
            }
        }
        cout << res;
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泥烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值