Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- #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, 0, 1, 0};
- int dy[] = {0, 1, 0, -1};
- const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 1005, L = 19;
- int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
- // -----------------------------------------------------------------------------
- int cost[N][N];
- void solve()
- {
- int n, m;
- cin >> n >> m;
- int sx, sy, ex, ey;
- cin >> sx >> sy >> ex >> ey;
- sx--, sy--, ex--, ey--;
- string grid[N];
- for (int i = 0; i < n; i++)
- {
- cin >> grid[i];
- }
- for (int i = 0; i < n; i++)
- {
- fill(cost[i], cost[i] + m, INF);
- }
- function<bool(int, int)> inside = [&](int x, int y)
- {
- return (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == '.');
- };
- deque<pi> dq;
- dq.push_back({sx, sy});
- cost[sx][sy] = 0;
- while (!dq.empty())
- {
- auto [x, y] = dq.front();
- dq.pop_front();
- // explore all directions first via A
- for (int i = 0; i < 4; i++)
- {
- int nx = x + dx[i];
- int ny = y + dy[i];
- if (inside(nx, ny) && cost[nx][ny] > cost[x][y])
- {
- cost[nx][ny] = cost[x][y];
- dq.push_front({nx, ny});
- }
- }
- // now via magic of B
- for (int dx = -2; dx <= 2; dx++)
- {
- for (int dy = -2; dy <= 2; dy++)
- {
- int nx = x + dx;
- int ny = y + dy;
- if (inside(nx, ny) && cost[nx][ny] > cost[x][y] + 1)
- {
- cost[nx][ny] = cost[x][y] + 1;
- dq.push_back({nx, ny});
- }
- }
- }
- }
- int ans = cost[ex][ey];
- cout << ((ans == (INF)) ? -1 : ans) << endl;
- return;
- }
- signed main()
- {
- // __START__;
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- cout.tie(NULL);
- int t = 1;
- // cin >> t;
- while (t--)
- {
- solve();
- }
- // __END__;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment