#include <bits/stdc++.h>
using namespace std;
struct Cell {
int r, c, dist;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<string> grid(n);
for (int i = 0; i < n; ++i) cin >> grid[i];
pair<int, int> start, goal;
cin >> start.first >> start.second >> goal.first >> goal.second;
start.first--; start.second--;
goal.first--; goal.second--;
vector<vector<int>> rowSafe(n), colSafe(m);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (grid[i][j] == '.')
rowSafe[i].push_back(j), colSafe[j].push_back(i);
queue<Cell> q;
vector<vector<int>> dist(n, vector<int>(m, -1));
dist[start.first][start.second] = 0;
q.push({start.first, start.second, 0});
vector<bool> rowUsed(n, false), colUsed(m, false);
int dr[4] = {-1, 1, 0, 0};
int dc[4] = {0, 0, -1, 1};
while (!q.empty()) {
auto [r, c, d] = q.front(); q.pop();
if (r == goal.first && c == goal.second) {
cout << d << "\n";
return 0;
}
for (int i = 0; i < 4; ++i) {
int nr = r + dr[i], nc = c + dc[i];
if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == '.' && dist[nr][nc] == -1) {
dist[nr][nc] = d + 1;
q.push({nr, nc, d + 1});
}
}
if (!rowUsed[r]) {
rowUsed[r] = true;
for (int nc : rowSafe[r]) {
if (dist[r][nc] == -1) {
dist[r][nc] = d + 1;
q.push({r, nc, d + 1});
}
}
}
#include <bits/stdc++.h>
using namespace std;
struct Cell {
int r, c, dist;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<string> grid(n);
for (int i = 0; i < n; ++i) cin >> grid[i];
int sr, sc, gr, gc;
cin >> sr >> sc >> gr >> gc;
sr--; sc--; gr--; gc--;
if (grid[sr][sc] != '.' || grid[gr][gc] != '.') {
cout << -1 << "\n";
return 0;
}
vector<vector<int>> rowSafe(n), colSafe(m);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (grid[i][j] == '.')
rowSafe[i].push_back(j), colSafe[j].push_back(i);
queue<Cell> q;
vector<vector<int>> dist(n, vector<int>(m, -1));
dist[sr][sc] = 0;
q.push({sr, sc, 0});
vector<bool> rowUsed(n, false), colUsed(m, false);
int dr[4] = {-1, 1, 0, 0};
int dc[4] = {0, 0, -1, 1};
while (!q.empty()) {
auto [r, c, d] = q.front(); q.pop();
if (r == gr && c == gc) {
cout << d << "\n";
return 0;
}
for (int i = 0; i < 4; ++i) {
int nr = r + dr[i], nc = c + dc[i];
if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == '.' && dist[nr][nc] == -1) {
dist[nr][nc] = d + 1;
q.push({nr, nc, d + 1});
}
}
if (!rowUsed[r]) {
rowUsed[r] = true;
for (int nc : rowSafe[r]) {
if (dist[r][nc] == -1) {
dist[r][nc] = d + 1;
q.push({r, nc, d + 1});
}
}
}
if (!colUsed[c]) {
colUsed[c] = true;
for (int nr : colSafe[c]) {
if (dist[nr][c] == -1) {
dist[nr][c] = d + 1;
q.push({nr, c, d + 1});
}
}
}
}
cout << -1 << "\n";
return 0;
}
if (!colUsed[c]) {
colUsed[c] = true;
for (int nr : colSafe[c]) {
if (dist[nr][c] == -1) {
dist[nr][c] = d + 1;
q.push({nr, c, d + 1});
}
}
}
}
cout << -1 << "\n";
return 0;
}