#include using namespace std; using point = pair; const vector dx{1, 0, -1, 0}, dy{0, 1, 0, -1}; int main() { constexpr int inf = 1e9; int h, w, ra, ca, rb, cb; cin >> h >> w >> ra >> ca >> rb >> cb; ra--; ca--; rb--; cb--; vector s(h); for (int i = 0; i < h; i++) { cin >> s.at(i); } vector d(h, vector(w, inf)), db(h, vector(w, inf)), dloop(h, vector(w, inf)); queue q; d.at(ra).at(ca) = 0; q.emplace(ra, ca); while (not q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int newx = x + dx.at(i), newy = y + dy.at(i); if (s.at(newx).at(newy) == '#') continue; if (d.at(newx).at(newy) != inf) continue; d.at(newx).at(newy) = d.at(x).at(y) + 1; q.emplace(newx, newy); } } const int dist = d.at(rb).at(cb); if (dist == inf) { cout << -1 << endl; return 0; } db.at(rb).at(cb) = 0; q.emplace(rb, cb); while (not q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int newx = x + dx.at(i), newy = y + dy.at(i); if (s.at(newx).at(newy) == '#') continue; if (db.at(newx).at(newy) != inf) continue; db.at(newx).at(newy) = db.at(x).at(y) + 1; q.emplace(newx, newy); } } vector> v(2 * h * w), v_back(h * w), v_front(h * w); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (d.at(i).at(j) == inf or db.at(i).at(j) == inf) continue; int d_total = d.at(i).at(j) + db.at(i).at(j); if (abs(d.at(i).at(j) - db.at(i).at(j)) < dist) { v.at(d.at(i).at(j) - db.at(i).at(j) + h * w).push_back(d_total); } else if (d.at(i).at(j) - db.at(i).at(j) > 0) { v_back.at(d.at(i).at(j)).push_back(d_total); } else { v_front.at(db.at(i).at(j)).push_back(d_total); } } } int ans = inf; for (int i = 0; i < 2 * h * w; i++) { sort(v.at(i).begin(), v.at(i).end()); if (v.at(i).size() >= 2) { ans = min(ans, v.at(i).at(0) + v.at(i).at(1)); } if (i >= h * w) continue; sort(v_back.at(i).begin(), v_back.at(i).end()); if (v_back.at(i).size() >= 2) { ans = min(ans, v_back.at(i).at(0) + v_back.at(i).at(1)); } sort(v_front.at(i).begin(), v_front.at(i).end()); if (v_front.at(i).size() >= 2) { ans = min(ans, v_front.at(i).at(0) + v_front.at(i).at(1)); } } int x_erase = rb, y_erase = cb, d_erase = dist; while (d_erase) { s.at(x_erase).at(y_erase) = '#'; for (int i = 0; i < 4; i++) { int newx = x_erase + dx.at(i), newy = y_erase + dy.at(i); if (s.at(newx).at(newy) == '#') continue; if (d.at(newx).at(newy) >= d_erase) continue; x_erase = newx; y_erase = newy; d_erase--; break; } } s.at(rb).at(cb) = '.'; dloop.at(ra).at(ca) = 0; q.emplace(ra, ca); while (not q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int newx = x + dx.at(i), newy = y + dy.at(i); if (s.at(newx).at(newy) == '#') continue; if (dloop.at(newx).at(newy) != inf) continue; if (x == ra and y == ca and newx == rb and newy == cb) continue; dloop.at(newx).at(newy) = dloop.at(x).at(y) + 1; q.emplace(newx, newy); } } ans = min(ans, dist + dloop.at(rb).at(cb)); if (ans == inf) { cout << -1 << endl; } else { cout << ans << endl; } }