#include <fstream>
using namespace std;
ifstream in("car.in");
ofstream out("car.out");
const int nmax = 506;
int a[nmax][nmax], b[nmax][nmax], n, m, x1, x2, y11, y2, rasp;
int q[2][8 * nmax * nmax];
int dir[8][2]={{0, 1},
{1, 1},
{1, 0},
{1, -1},
{0, -1},
{-1, -1},
{-1, 0},
{-1, 1}};
int cod(int x, int y, int dir)
{
return (((x<<9)+y)<<3)+dir;
}
struct str{
int x, y, dir;
};
str deco(int a)
{
str s;
s.dir = a & 7;
a >>= 3;
s.y = a & 511;
a >>= 9;
s.x = a;
return s;
}
inline bool on_map(int x, int y)
{
if(!x || !y || x>n || y>m)
return 0;
return 1;
}
int main()
{
int player_unu=0;
in>>n>>m;
in>>x1>>y11>>x2>>y2;
if(x1==x2 && y11==y2)
{
out << "0\n";
return 0;
}
for(int i = 1; i<=n; i++)
{
for(int j = 1; j<=m; j++)
{
in>>a[i][j];
}
}
for(int i = 0; i<=7; i++)
{
q[0][++q[0][0]] = cod(x1, y11, i);
}
for(int i = 0; !b[x2][y2] && q[i&1][0]; i++, rasp++)
{
while(q[i&1][0])
{
int nod = q[i&1][q[i&1][0]];
q[i&1][0]--;
str s = deco(nod);
if((b[s.x][s.y]&(1<<s.dir)))
continue;
b[s.x][s.y] += (1<<s.dir);
s.x += dir[s.dir][0];
s.y += dir[s.dir][1];
if(on_map(s.x, s.y) && !a[s.x][s.y] && !(b[s.x][s.y]&(1<<s.dir)))
{
q[i&1][++q[i&1][0]] = cod(s.x, s.y, s.dir);
}
s.x -= dir[s.dir][0];
s.y -= dir[s.dir][1];
for(int j =- 1; j<=1; j+=2)
{
s.dir += j + 8;
s.dir &= 7;
if(!(b[s.x][s.y]&(1<<s.dir)))
{
q[(i+1)&1][++q[(i+1)&1][0]] = cod(s.x, s.y, s.dir);
}
s.dir = s.dir - j + 8;
s.dir &= 7;
}
}
}
if(!b[x2][y2])
rasp = 0;
out<<rasp - 1<<"\n";
return player_unu;
}