#include <cstdio>
#include <vector>
#define INF 1<<30
#define VMax 1000000
#define NMax 502
#define DMax 8
#define ushort unsigned short
#define ABS(x)((x)>0?(x):(-(x)))
using namespace std;
struct car
{
ushort x,y;
char k0,k1;
};
vector<car>v[VMax+1];
int best[NMax+1][NMax+1][DMax+1];
int cost[DMax+1][DMax+1];
char a[NMax+1][NMax+1];
int dirx[8]={-1,-1,0,1,1,1,0,-1};
int 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;
}
}
int main(){
freopen("car.in","r",stdin);
freopen("car.out","w",stdout);
int ans,i,j,k,N,M,x0,y0,xf,yf,x,y,xc,yc,k0,k1,sum;
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)
{
scanf("%d",&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)
{
while( !v[i].empty() )
{
temp = v[i].back();
v[i].pop_back();
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 )
{
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);
}
}
}
}
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;
}