3 条题解
-
0
#include <bits/stdc++.h> #define int long long // 仅在需要大整数时使用,memset 数组为 0x3f 时去掉 #define INF 0x3f3f3f3f #define PII pair<int, int> #define ULL unsigned long long #define PIII tuple<int, int, int> #define all(v) v.begin(), v.end() #define debug(a) cout << #a << " = " << a << endl; using namespace std; constexpr int M = 1 * 1e3 + 10; char mp[M][M]; bool st[M][M][2]; int n, m; int sx, sy, ex, ey; int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; struct node { int x, y; int step; bool flag; }; bool checkin(int x, int y) { return x > 0 && y > 0 && x <= n && y <= m; } int bfs() { queue<node> q; q.push({sx, sy, 0, 0}); st[sx][sy][0] = 1; while (q.size()) { auto [x, y, step, flag] = q.front(); q.pop(); if (x == ex && y == ey) return step; //Walk for (int i = 0; i < 4; i ++) { node ne; ne.x = x + dir[i][0]; ne.y = y + dir[i][1]; if (!checkin(ne.x, ne.y)) continue; if (mp[ne.x][ne.y] == '#') continue; if (st[ne.x][ne.y][0]) continue; st[ne.x][ne.y][0] = 1; ne.step = step + 1; ne.flag = 0; q.push(ne); } //Jump if (!flag) { for (int i = 0; i < 4; i ++) { node ne; ne.x = x + dir[i][0] * 2; ne.y = y + dir[i][1] * 2; if (!checkin(ne.x, ne.y)) continue; if (mp[ne.x][ne.y] == '#') continue; if (st[ne.x][ne.y][1]) continue; st[ne.x][ne.y][1] = 1; ne.step = step + 1; ne.flag = 1; q.push(ne); } } } return -1; } void solve() { cin >> n >> m; for (int i = 1; i <= n; i ++) { for (int j = 1; j <= m; j ++) { cin >> mp[i][j]; if (mp[i][j] == 'S') sx = i, sy = j; if (mp[i][j] == 'E') ex = i, ey = j; } } cout << bfs() << '\n'; } signed main() { ios::sync_with_stdio(0); cin.tie(nullptr), cout.tie(nullptr); int _ = 1; // cin >> _; while (_--) { solve(); } return 0; } /** * author: Nijika_jia * description: C++17 Algorithm Template for Competitive Programming */
信息
- ID
- 5629
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 27
- 已通过
- 4
- 上传者