#include namespace { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic pop using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; constexpr int INF = 1001001001; template // cost in [0, k) int kBFS(const vector>>& g, int s, int goal) { static_assert(k >= 1); const int n = g.size(); vector dist(n, INF); vector q[2 * k]; dist[s] = 0; q[0].emplace_back(s); for (int dist_cur = 0, ptr = 0;;) { const auto qb = q + ptr; while (!qb[0].empty()) { int u = qb[0].back(); qb[0].pop_back(); if (dist[u] != dist_cur) continue; if (u == goal) return dist_cur; for (auto [v, c] : g[u]) { int nd = dist_cur + c; if (nd < dist[v]) { dist[v] = nd; qb[c].emplace_back(v); } } } do { dist_cur++; ptr++; if (ptr == 2 * k) return -1; } while (q[ptr].empty()); if (ptr > k) { for (int i = ptr; i < 2 * k; i++) { swap(q[i], q[i - ptr]); } ptr = 0; } } } } int main() { ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; int sx, sy, gx, gy; cin >> sx >> sy >> gx >> gy; sx--, sy--, gx--, gy--; char s[2010][2010]; rep(i, h) cin >> s[i]; vector>> to(h * w * 2); const int tot = h * w; rep(i, h - 1) rep(j, w) { int v = tot + i * w + j; to[v + w].emplace_back(v, 0); } rep(i, h) rep(j, w) if (s[i][j] == '.') { int v = i * w + j; to[tot + v].emplace_back(v, 0); } short i_last[2000][2000]; rep(j, w) { int il = 0; rep(i, h) { if (s[i][j] == '.') il = i; i_last[i][j] = il; } } rep(i, h) rep(j, w) if (s[i][j] == '.') { for(int dj: {1, -1}) { int nj = j + dj; if (!(0 <= nj && nj < w)) continue; to[i*w + j].emplace_back(tot + min(h-1, i+1)*w + nj, 0); int il = i_last[min(h-1, i+1)][nj]; nj += dj; if (0 <= nj && nj < w) { int e = max(0, i - il); to[i*w + j].emplace_back(tot + min(h-1, il + 1 + e / 2)*w + nj, 0); to[i*w + j].emplace_back(tot + min(h-1, i+1)*w + nj, 1); } } if (w != 1) { to[i*w + j].emplace_back(tot + min(h-1, i+1)*w + j, 1); } } int ans = kBFS(to, sx*w + sy, gx * w + gy); cout << ans << '\n'; }