跳到正文

题解

题解:P9351 [JOI 2023 Final] 迷宫 / Maze

__Jasmine约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年3月30日
收录
2025年12月12日
更新
2026年9月28日
篇幅
约 4 分钟
获赞
2
题目
P9351

版本

  1. v1当前

P9351。

这题对于 n=1n=1 就是直接 0-1bfs 即可。

这题的暴力是 O(rcn2)O(rcn^2) 的 0-1bfs,直接建 (x,y)(x, y) 向可行范围里每一个点连价值为 11 的边,其他就是价值为 00 的四联通边。

然后发现其实只需要对可行范围最外面一圈的边连边就可以了,因为你往正方形内部连边本质上还是要走向可行范围的边界,不如直接连上去。这样就是 O(rcn)O(rcn) 的了,由于 n=rcn=\sqrt{rc},所以相当于 rcrcrc\sqrt{rc}。这样就大概能过前六个点了。

而正解呢非常的有教育意义!

当我们走到一个正方形时,剩下的 nn 步可以八联通的走。

原理是:

  • 切比雪夫距离等价于可以八连通地走。
  • 然后某个方向切比雪夫距离在 nn 之内的点相当于一个 n×nn×n 的正方形的范围。
  • 所以跳到一个 n×nn×n 的正方形的范围中的某一点就相当于可以八连通走 nn 步。

发现这样走是可以覆盖可行范围内所有点的,所以在 0-1bfs 的时候多记一维四(八)联通即可。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int Dx[8] = {0, 0, 1, -1, 1, 1, -1, -1};
const int Dy[8] = {-1, 1, 0, 0, 1, -1, 1, -1};
const int N = 6e6 + 5;
vector<int> A[N], Vis[N];
int n, m, k, Sx, Sy, Ex, Ey;
inline bool In(int x, int y) { return (1 <= x && x <= n && 1 <= y && y <= m); }
struct Node {
  int x, y, D, H;
};
char C[N];
signed main() {
  //freopen("maze.in", "r", stdin);
  //freopen("maze.out", "w", stdout);
  ios_base::sync_with_stdio(false);
	cin.tie(nullptr), cout.tie(nullptr);
  cin >> n >> m >> k >> Sx >> Sy >> Ex >> Ey;
  for (int i = 1; i <= n; i++) {
    cin >> (C + 1);
    A[i].resize(m + 5), Vis[i].resize(m + 5);
    for (int j = 1; j <= m; j++)
      A[i][j] = C[j] == '#';
  }
  deque<Node> Q;
  Q.push_back({Sx, Sy, 0, 0});
  while (!Q.empty()) {
    Node t = Q.front();
    Q.pop_front();
    int x = t.x, y = t.y, D = t.D, H = t.H;
    if (Vis[x][y])
      continue;
    Vis[x][y] = 1;
    if (x == Ex && y == Ey)
      return cout << D << '\n', 0;
    if (H) {
      for (int i = 0; i < 8; i++) {
        int X = x + Dx[i], Y = y + Dy[i];
        if (In(X, Y) && !Vis[X][Y])
          Q.push_back({X, Y, D, H - 1});
      }
    } else {
      for (int i = 0; i < 4; i++) {
        int X = x + Dx[i], Y = y + Dy[i];
        if (In(X, Y) && !Vis[X][Y]) {
          if (A[X][Y])
            Q.push_back({X, Y, D + 1, k - 1});
          else
            Q.push_front({X, Y, D, 0});
        }
      }
    }
  }
}