#include using namespace std; using ll = long long; #define rep(i, n) for (ll i = 0; i < (n); i++) #define all(v) begin(v), end(v) const int MAX_P = 100000; int main() { int H, W; cin >> H >> W; array S, G; cin >> S[0] >> S[1]; --S[0], --S[1]; cin >> G[0] >> G[1]; --G[0], --G[1]; vector C(H); for (auto &s : C) cin >> s; if (S[0] > G[0]) { S[0] = H - 1 - S[0]; G[0] = H - 1 - G[0]; reverse(all(C)); } if (S[1] > G[1]) { S[1] = W - 1 - S[1]; G[1] = W - 1 - G[1]; for (auto &s : C) reverse(all(s)); } vector dist(H, vector(W, vector(H * W, array()))); using ai4 = array; rep(i,H){ rep(j,W){ rep(k,H*W){ rep(l,2)dist[i][j][k][l]=1e9; } } } dist[S[0]][S[1]][0][0] = 0; deque bfs; bfs.push_back(ai4{S[0], S[1], 0, 0}); auto move_ok = [&](int x, int y) -> bool { if (x < 0 || x >= H || y < 0 || y >= W) return false; return C[x][y] != '#'; }; while (!bfs.empty()) { auto [x, y, dA, f] = bfs.front(); bfs.pop_front(); int dC = dist[x][y][dA][f]; if (dA + 1 < H * W) { // A int x2 = x - 1, y2 = y; if (move_ok(x2, y2) && dist[x2][y2][dA + 1][f] > dC) { dist[x2][y2][dA + 1][f] = dC; bfs.push_front(ai4{x2, y2, dA + 1, f}); } } { // B int x2 = x + 1, y2 = y; if (move_ok(x2, y2) && dist[x2][y2][dA][f] > dC) { dist[x2][y2][dA][f] = dC; bfs.push_front(ai4{x2, y2, dA, f}); } } { // C int x2 = x, y2 = y - 1; if (move_ok(x2, y2) && dist[x2][y2][dA][f | 1] > dC + 1) { dist[x2][y2][dA][f | 1] = dC + 1; bfs.push_back(ai4{x2, y2, dA, f | 1}); } } { // D int x2 = x, y2 = y + 1; if (move_ok(x2, y2) && dist[x2][y2][dA][f] > dC) { dist[x2][y2][dA][f] = dC; bfs.push_front(ai4{x2, y2, dA, f}); } } } vector prime(MAX_P, true); prime[0] = prime[1] = 0; for (ll i = 2; i < MAX_P; i++) { if (!prime[i]) continue; for (ll j = i * i; j < MAX_P; j += i) prime[j] = 0; } vector pH, pW; rep(i, MAX_P - (G[0] - S[0])) { if (prime[i] && prime[i + (G[0] - S[0])]) pH.push_back(i); } rep(i, MAX_P - (G[1] - S[1])) { if (prime[i] && prime[i + (G[1] - S[1])]) pW.push_back(i); } int ans = 1e9; rep(i, H * W) { if (!i) continue; int c = dist[G[0]][G[1]][i][1]; auto itH = lower_bound(all(pH), i); auto itW = lower_bound(all(pW), c); if (itH != end(pH) && itW != end(pW)) { ans = min(ans, (*itH) * 2 + (G[0] - S[0]) + (*itW) * 2 + (G[1] - S[1])); } } if (ans == 1e9) cout << "-1\n"; else cout << ans << '\n'; }