#include #include #include #include #include #include using namespace std; template inline void for_nbd4(int x, int y, int lx, int ux, int ly, int uy, Callback f) { constexpr pair dxdy[] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; for (auto [dx, dy] : dxdy) { const int u = x + dx, v = y + dy; if (lx <= u && u < ux && ly <= v && v < uy) f(u, v); } } template inline void for_nbd4(int x, int y, int X, int Y, Callback f) { for_nbd4(x, y, 0, X, 0, Y, f); } template inline T sum_nbd4(int x, int y, int lx, int ux, int ly, int uy, Callback f) { constexpr pair dxdy[] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; T result{}; for (auto [dx, dy] : dxdy) { const int u = x + dx, v = y + dy; if (lx <= u && u < ux && ly <= v && v < uy) result += f(u, v); } return result; } template inline T sum_nbd4(int x, int y, int X, int Y, Callback f) { return sum_nbd4(x, y, 0, X, 0, Y, f); } int main() { int h, w, sx, sy, gx, gy; cin >> h >> w >> sx >> sy >> gx >> gy; sx--; sy--; gx--; gy--; vector S(h); for (int i = 0; i < h; i++) cin >> S[i]; int dist[h][w], count[h][w]; pair from[h][w]; constexpr int INF = 1<<30; priority_queue > pq; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (i == sx && j == sy) { dist[i][j] = 0; count[i][j] = 1; from[i][j] = {-1, -1}; pq.push({0, i, j}); } else { dist[i][j] = INF; count[i][j] = 0; } while (!pq.empty()) { auto [d, x, y] = pq.top(); pq.pop(); d = -d; if (dist[x][y] < d) continue; for_nbd4(x, y, h, w, [d=d, x=x, y=y, &S, &dist, &pq, &count, &from](int u, int v) { if (S[u][v] == '#') return; if (dist[u][v] > dist[x][y] + 1) { dist[u][v] = dist[x][y] + 1; count[u][v] = count[x][y]; from[u][v] = {x, y}; pq.push({-dist[u][v], u, v}); } else if (dist[u][v] == dist[x][y] + 1) { count[u][v] += count[x][y]; } }); } // for (int i = 0; i < h; i++) // for (int j = 0; j < w; j++) // cerr << i << ' ' << j << ' ' << dist[i][j] << ' ' << count[i][j] << endl; if (count[gx][gy] == 0) cout << -1 << endl; else if (count[gx][gy] > 1) cout << 2 * dist[gx][gy] << endl; else { int x = gx, y = gy; for (;;) { tie(x, y) = from[x][y]; if (x == sx && y == sy) break; if (sum_nbd4(x, y, h, w, [&](int u, int v) {return int(S[u][v] == '.');}) > 2) { cout << 2 * dist[gx][gy] + 2 << endl; return 0; } S[x][y] = '#'; } const int d0 = dist[gx][y]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) dist[i][j] = (i == sx && j == sy) ? 0 : INF; pq.push({0, sx, sy}); while (!pq.empty()) { auto [d, x, y] = pq.top(); pq.pop(); d = -d; if (dist[x][y] < d) continue; for_nbd4(x, y, h, w, [d=d, x=x, y=y, &S, &dist, &pq](int u, int v) { if (S[u][v] == '#') return; if (dist[u][v] > dist[x][y] + 1) { dist[u][v] = dist[x][y] + 1; pq.push({-dist[u][v], u, v}); } }); } if (dist[gx][gy] == INF) cout << "-1" << endl; else cout << d0 + dist[gx][gy] << endl; } }