# include <algorithm>
# include <bitset>
# include <cstdio>
# include <cstring>
# include <queue>
using namespace std;
# define x first
# define y second
# define verf ++poz == hg ? fread ( ch, 1, hg, stdin ), poz = 0 : 0
typedef pair <int, int> PR ;
const char *FIN = "car.in", *FOU = "car.out" ;
const int dx[] = { -1 , -1 , 0 , 1 , 1 , 1 , 0 , -1 } ;
const int dy[] = { 0 , 1 , 1 , 1 , 0 , -1 , -1 , -1 } ;
const int hg = 1 << 13 ;
queue <int> Q[2] ;
int D[8][501][501] ;
bitset <501> V[501] ;
int N, M, poz ;
PR I, F ;
int biti (int var, int bit) {
return (var << bit) ;
}
int ls (int var, int bit) {
return (var >> bit) ;
}
char ch[ hg ] ;
inline void cit ( int &x ) {
if ( ch[0] == '\0' ) fread ( ch, 1, hg, stdin ) ;
else for ( ; ch[poz] < '0' || ch[poz] > '9' ; verf ) ;
for ( x = 0 ; ch[poz] >= '0' && ch[poz] <= '9' ; x = x * 10 + ch[poz] - '0', verf ) ;
}
int main (void) {
freopen (FIN, "r", stdin) ;
cit (N), cit (M), cit (I.x), cit (I.y), cit (F.x), cit (F.y) ;
for (int i = 1; i <= N; ++i) {
for (int j = 1, k; j <= N; ++j) {
cit (k), V[i][j] = k ;
}
}
memset (D, 0x3f, sizeof (D)) ;
for (int i = 0; i < 8; ++i) {
Q[0].push (biti (I.x, 0) + biti (I.y, 9) + biti (i, 18)) ;
D[i][I.x][I.y] = 0 ;
}
for (int l = 0; Q[0].size () + Q[1].size () > 0; ++l) {
for (int ind = l & 1; !Q[ind].empty (); Q[ind].pop ()) {
int P = Q[ind].front (), d = ls (P, 18);
PR rec (ls (P, 0) & biti (1, 9) - 1, ls (P, 9) & biti (1, 9) - 1);
if (rec == F) {
fprintf (fopen (FOU, "w"), "%d", l) ;
return 0 ;
}
PR act = rec ;
act.x += dx[d], act.y += dy[d] ;
if (act.x > 0 && act.y > 0 && act.x <= N && act.y <= M) {
if (V[act.x][act.y] == 0 && D[d][act.x][act.y] > l) {
D[d][act.x][act.y] = l ;
Q[ind].push (biti (act.x, 0) + biti (act.y, 9) + biti (d, 18)) ;
}
}
if (D[d + 1 & 7][rec.x][rec.y] > l + 1) {
D[d + 1 & 7][rec.x][rec.y] = l + 1;
Q[ind ^ 1].push (biti (rec.x, 0) + biti (rec.y, 9) + biti (d + 1 & 7, 18)) ;
}
if (D[d + 7 & 7][rec.x][rec.y] > l + 1) {
D[d + 7 & 7][rec.x][rec.y] = l + 1;
Q[ind ^ 1].push (biti (rec.x, 0) + biti (rec.y, 9) + biti (d + 7 & 7, 18)) ;
}
}
}
fprintf (fopen (FOU, "w"), "%d", -1) ;