Dmaxiya

P8673 [蓝桥杯 2018 国 C] 迷宫与陷阱 参考代码

Feb 6th, 2026
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define endl '\n'
  5.  
  6. typedef long long LL;
  7. const int maxn = 1000 + 100;
  8. const int INF = 0x3f3f3f3f;
  9. struct Node {
  10.     int x, y, z;
  11.     Node() {}
  12.     Node(int x, int y, int z) : x(x), y(y), z(z) {}
  13. };
  14.  
  15. int n, k;
  16. char str[maxn][maxn];
  17. int dis[maxn][maxn][20];
  18. queue<Node> que;
  19. const int dir[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};
  20.  
  21. bool in(int x, int y) {
  22.     return x >= 0 && x < n && y >= 0 && y < n;
  23. }
  24.  
  25. int main() {
  26. #ifdef ExRoc
  27.     freopen("test.txt", "r", stdin);
  28. #endif // ExRoc
  29.     ios::sync_with_stdio(false);
  30.  
  31.     cin >> n >> k;
  32.     for (int i = 0; i < n; ++i) {
  33.         cin >> str[i];
  34.     }
  35.     memset(dis, 0x3f, sizeof(dis));
  36.     que.push({0, 0, 0});
  37.     dis[0][0][0] = 0;
  38.     while (!que.empty()) {
  39.         Node tmp = que.front();
  40.         que.pop();
  41.         for (int i = 0; i < 4; ++i) {
  42.             int x = tmp.x + dir[i][0];
  43.             int y = tmp.y + dir[i][1];
  44.             int z = max(tmp.z - 1, 0);
  45.             if (!in(x, y) || str[x][y] == '#') {
  46.                 continue;
  47.             }
  48.             if (str[x][y] == '%') {
  49.                 z = k + 1;
  50.             }
  51.             if (str[x][y] == 'X') {
  52.                 if (z == 0) {
  53.                     continue;
  54.                 }
  55.             }
  56.             if (dis[x][y][z] > dis[tmp.x][tmp.y][tmp.z] + 1) {
  57.                 dis[x][y][z] = dis[tmp.x][tmp.y][tmp.z] + 1;
  58.                 que.push({x, y, z});
  59.             }
  60.         }
  61.     }
  62.     int ans = INF;
  63.     for (int i = 0; i <= k; ++i) {
  64.         ans = min(ans, dis[n - 1][n - 1][i]);
  65.     }
  66.     cout << (ans == INF ? -1 : ans) << endl;
  67.  
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment