AT_abc400_d [ABC400D] Takahashi the Wall Breaker 题解

· · 题解

题目大意

高桥准备去鱼店买鳗鱼。

他居住的城镇被划分为 H 行和 W 列的网格。每个格子要么是一条路,要么是一堵墙。

让我们将顶部 (1\leq i \leq H) 的第 i 行的单元格和左侧 (1\leq j \leq W) 的第 j 列表示为单元格 (i, j)。

有关每个单元格的信息由 H 字符串 S_1,S_ 2,\ldots,S_H 提供,每个字符串的长度为 W。具体来说,如果 S_i(1\leq i \leq H,1\leq j\leq W) 的第 j 个字符是 .,则单元格 (i, j) 是道路;如果是 #,单元格 (i, j) 是墙。

他可以按任何顺序重复执行下列两种行动:

移动到邻近的小区(上,下,左,或右),在城镇内,是一条道路。

他从单元格 (A, B) 开始,并且希望移动到单元格 (C, D) 中的鱼店。

可以保证,他开始的格子和鱼店的格子都是 .。 找到他到达鱼店所需要的最小前踢次数。

解题思路

这道题非常 amazing 啊,我以为不能直接爆搜,需要非常难的优化啊,结果。。。

相信一定有人跟我一样,那就让我们来看看怎么做吧。

首先题目说可以破坏连续两个墙壁(容易破产),那我们直接向前走两步就可以了(不用判道路和墙壁,毕竟再高的墙壁也有人能越过),最后开一个数组存储经过每个点所需的最小步数,用来剪枝,再使用 priority_queue 按步数从大到小排序优化即可(如果从小到大的话他会把所有情况都给跑满)。

CODE:

#include <bits/stdc++.h>
using namespace std;
#define int long long
int vis[1010][1010];
char a[1010][1010];
struct node {
    int x, y, step;
    inline bool operator < (const node t) const {
        return step > t.step;
    }
};
priority_queue<node> q;
signed main() {
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int n, m, sx, sy, ex, ey;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> a[i][j];
            vis[i][j] = 1e9;
        }
    }
    cin >> sx >> sy >> ex >> ey;
    q.push({sx, sy, 0});
    while (!q.empty()) {
        node t = q.top();
        q.pop();
        if (t.step >= vis[t.x][t.y]) {
            continue;
        }
        vis[t.x][t.y] = t.step;
        if (a[t.x][t.y - 1] == '.' && t.y - 1 >= 1) {
            q.push({t.x, t.y - 1, t.step});
        }
        if (a[t.x][t.y + 1] == '.' && t.y + 1 <= m) {
            q.push({t.x, t.y + 1, t.step});
        }
        if (a[t.x - 1][t.y] == '.' && t.x - 1 >= 1) {
            q.push({t.x - 1, t.y, t.step});
        }
        if (a[t.x + 1][t.y] == '.' && t.x + 1 <= n) {
            q.push({t.x + 1, t.y, t.step});
        }
        if (t.y - 1 >= 1) {
            q.push({t.x, t.y - 1, t.step + 1});
        }
        if (t.y - 2 >= 1) {
            q.push({t.x, t.y - 2, t.step + 1});
        }
        if (t.y + 1 <= m) {
            q.push({t.x, t.y + 1, t.step + 1});
        }
        if (t.y + 2 <= m) {
            q.push({t.x, t.y + 2, t.step + 1});
        }
        if (t.x - 1 >= 1) {
            q.push({t.x - 1, t.y, t.step + 1});
        }
        if (t.x - 2 >= 1) {
            q.push({t.x - 2, t.y, t.step + 1});
        }
        if (t.x + 1 <= n) {
            q.push({t.x + 1, t.y, t.step + 1});
        }
        if (t.x + 2 <= n) {
            q.push({t.x + 2, t.y, t.step + 1});
        }
    }
    cout << vis[ex][ey];
    return 0;
}