Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://atcoder.jp/contests/abc246/tasks/abc246_e
- // 0-1 BFS
- #include <bits/stdc++.h>
- // #include <atcoder/all>
- using namespace std;
- #define int long long
- #define all(x) (x).begin(), (x).end()
- typedef vector<int> vi;
- typedef vector<vi> vvi;
- typedef vector<pair<int, int>> vpi;
- typedef pair<int, int> pi;
- typedef pair<pi, int> ppi;
- #define f first
- #define s second
- #define pb push_back
- #define endl "\n"
- #define yes cout << "YES" << endl
- #define no cout << "NO" << endl
- int dx[] = {-1, 1, -1, 1};
- int dy[] = {-1, 1, 1, -1};
- const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 2e5 + 5, L = 19;
- int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
- // -----------------------------------------------------------------------------
- void solve()
- {
- int n, ax, ay, bx, by;
- cin >> n >> ax >> ay >> bx >> by;
- ax--, ay--, bx--, by--;
- vector<string> grid(n);
- for (int i = 0; i < n; i++)
- {
- cin >> grid[i];
- }
- auto inside = [&](int nx, int ny) -> bool
- {
- return (nx >= 0 && nx < n && ny >= 0 && ny < n && grid[nx][ny] != '#');
- };
- // x, y, direction -> unique state
- vector<vvi> dis(n, vvi(n, vi(4, INF)));
- vector<vvi> vis(n, vvi(n, vi(4, 0)));
- deque<ppi> dq;
- for (int i = 0; i < 4; i++)
- {
- int nx = ax + dx[i];
- int ny = ay + dy[i];
- if (inside(nx, ny))
- {
- if (dis[nx][ny][i] > 1)
- {
- dis[nx][ny][i] = 1;
- dq.push_back({{nx, ny}, i});
- }
- }
- }
- while (!dq.empty())
- {
- auto cur = dq.front();
- dq.pop_front();
- int x = cur.f.f;
- int y = cur.f.s;
- int d = cur.s;
- if (x == bx && y == by)
- {
- cout << dis[x][y][d] << endl;
- return;
- }
- if (vis[x][y][d])
- {
- continue;
- }
- vis[x][y][d] = 1;
- int curd = dis[x][y][d];
- for (int i = 0; i < 4; i++)
- {
- int nx = x + dx[i];
- int ny = y + dy[i];
- if (!inside(nx, ny))
- {
- continue;
- }
- int newd = curd + (i == d ? 0 : 1);
- if (dis[nx][ny][i] > newd)
- {
- dis[nx][ny][i] = newd;
- if (i == d)
- {
- dq.push_front({{nx, ny}, i});
- }
- else
- {
- dq.push_back({{nx, ny}, i});
- }
- }
- }
- }
- cout << -1 << endl;
- }
- signed main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int t = 1;
- // cin >> t;
- while (t--)
- {
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment