#include #include 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) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() template void chmax(T& a, const T& b) {a = max(a, b);} template void chmin(T& a, const T& b) {a = min(a, b);} using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1}; constexpr int INF = 1001001001; int dist[1000][1000][6]; int main() { ios::sync_with_stdio(false); cin.tie(0); rep(i, 1000) rep(j, 1000) rep(k, 6) dist[i][j][k] = INF; int h, w; cin >> h >> w; int sx, sy; cin >> sx >> sy; sx--, sy--; int gx, gy; cin >> gx >> gy; gx--, gy--; vector s(h); rep(i, h) cin >> s[i]; queue> q; auto push = [&](int i, int j, int k, int d) { if (dist[i][j][k] == INF) { dist[i][j][k] = d; q.emplace(i, j, k); } }; push(sx, sy, 4, 0); while(!q.empty()) { auto [i, j, k] = q.front(); q.pop(); int nd = dist[i][j][k] + 1; rep(direction, 4) { int ni = i + dx[direction], nj = j + dy[direction]; if (!(0 <= ni && ni < h && 0 <= nj && nj < w && s[ni][nj] == '.')) { continue; } int nk = ( k == 4 ? direction : k == 5 ? direction ^ 2 : ((direction ^ k) & 1) ? k : direction == k ? 5 : 4 ); push(ni, nj, nk, nd); } } int ans = dist[gx][gy][4]; if (ans == INF) ans = -1; cout << ans << '\n'; }