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;
}

原文地址:https://www.cnblogs.com/Knight02/p/15799049.html