#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)); 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); } } if (d.at(rb).at(cb) == 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(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; v.at(d.at(i).at(j)).push_back(d.at(i).at(j) + db.at(i).at(j)); } } int ans = inf; for (int i = 0; i < h * w; i++) { if (v.at(i).size() <= 1) continue; sort(v.at(i).begin(), v.at(i).end()); ans = min(ans, v.at(i).at(0) + v.at(i).at(1)); } if (ans == inf) { cout << -1 << endl; } else { cout << ans << endl; } }