#include <cstdio>
#include <cctype>
#include <vector>
#define INF 1<<30
#define VMax 500000
#define NMax 502
#define DMax 8
#define DIM 10000
#define ushort unsigned short
using namespace std;
char buff[DIM];
int poz;
struct car
{
ushort x,y;
char k0,k1;
};
vector<car>v[VMax+1];
int best[NMax+1][NMax+1][DMax+1];
char cost[DMax+1][DMax+1];
char a[NMax+1][NMax+1];
char dirx[8]={-1,-1,0,1,1,1,0,-1};
char diry[8]={0,1,1,1,0,-1,-1,-1};
void Precalc()
{
int i,j,x;
for(i = 0; i < 8; ++i)
for(x = 0; x < 5; ++x)
{
j = i+x;
if( j > 7 ) j -= 8;
cost[i][j] = x;
j = i-x;
if( j < 0 ) j += 8;
cost[i][j] = x;
}
}
void Read(char& numar)
{
numar = 0;
while(!isdigit(buff[poz]))
if(++poz==DIM) fread(buff,1,DIM,stdin),poz=0;
while(isdigit(buff[poz]))
{
numar = numar*10 + buff[poz] - '0';
if(++poz==DIM) fread(buff,1,DIM,stdin),poz=0;
}
}
int main(){
freopen("car.in","r",stdin);
freopen("car.out","w",stdout);
int ans,i,j,k,N,M,x0,y0,xf,yf,sum,x,y,xc,yc,k0,k1;
car temp;
scanf("%d %d",&N,&M);
scanf("%d %d %d %d",&x0,&y0,&xf,&yf);
Precalc();
for(i = 1; i <= N; ++i)
for(j = 1; j <= M; ++j)
{
Read(a[i][j]);
for(k = 0; k < 8; ++k)
best[i][j][k] = -a[i][j]-1;
}
for(k = 0; k < 8; ++k) best[x0][y0][k] = 0;
temp.x = x0;
temp.y = y0;
for(k = 0; k < 8; ++k)
if( best[ x0+dirx[k] ][ y0+diry[k] ][k] == -1 )
{
temp.k1 = temp.k0 = k;
v[0].push_back(temp);
}
for(i = 0; i < VMax; ++i)
{
j = 0;
while( j < v[i].size() )
{
temp = v[i][j];
x = temp.x;
y = temp.y;
k0 = temp.k0;
k1 = temp.k1;
if( best[ x+dirx[k1] ][ y+diry[k1] ][k1] == -1 )
{
xc = x+dirx[k1];
yc = y+diry[k1];
best[xc][yc][k1] = i;
for(k = 0; k < 8; ++k)
if( best[ xc+dirx[k] ][ yc+diry[k] ][k] == -1 && cost[k0][k] <= 2 )
{
sum = best[xc][yc][k1] + cost[k1][k];
temp.x = xc;
temp.y = yc;
temp.k0 = k1;
temp.k1 = k;
v[sum].push_back(temp);
}
}
++j;
}
}
for(ans = INF, k = 0; k < 8; ++k)
if( best[xf][yf][k] < ans && best[xf][yf][k] > -1 ) ans = best[xf][yf][k];
if(ans==INF) printf("-1\n");
else printf("%d",ans);
return 0;
}