#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int nmax = 505;
int n, m;
int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};
int a[nmax][nmax];
int D[nmax][nmax][8];
bool iq[nmax][nmax][8];
inline int cost(int pd, int nd) {
if (nd < pd)
swap(nd, pd);
if (nd - pd < pd - nd + 8)
return nd - pd;
return pd - nd + 8;
}
bool valid(int x, int y) {
return (x >= 1 && x <= n) && (y >= 1 && y <= m) && a[x][y] == 0;
}
int main() {
int x1, y1, x2, y2;
freopen("car.in", "r", stdin);
freopen("car.out", "w", stdout);
scanf("%d %d", &n, &m);
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%d", &a[i][j]);
}
}
memset(D, INF, sizeof(D));
queue<pair<pair<int, int>, int> > q;
for (int k = 0; k < 8; k++) {
D[x1][y1][k] = 0;
int x = x1 + dx[k];
int y = y1 + dy[k];
if (valid(x, y)) {
q.push(make_pair(make_pair(x, y), k));
iq[x][y][k] = true;
D[x][y][k] = 0;
}
}
while (!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int pd = q.front().second;
iq[x][y][pd] = false;
q.pop();
for (int k = 0; k < 8; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
int cst = cost(pd, k);
if (valid(nx, ny)) {
if (D[nx][ny][k] > D[x][y][pd] + cst) {
D[nx][ny][k] = D[x][y][pd] + cst;
if (!iq[nx][ny][k]) {
iq[nx][ny][k] = true;
q.push(make_pair(make_pair(nx, ny), k));
}
}
}
}
}
int ans = INF;
for (int k = 0; k < 8; k++) {
ans = min(ans, D[x2][y2][k]);
}
if (ans == INF)
printf("-1\n");
else
printf("%d\n", ans);
return 0;
}