#include <bits/stdc++.h>
#include <atcoder/all>
using namespace std;
using namespace atcoder;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)
#define ALLOF(c) (c).begin(), (c).end()
typedef long long ll;
typedef unsigned long long ull;
//using mint = modint1000000007;
//using mint = modint998244353;

static const ll INF = 1e18;

int H, W;
int sy, sx;
int gy, gx;
string field[1005];

ll dist[1005][1005][6];

int vy[4] = {-1,1,0,0};
int vx[4] = {0,0,-1,1};

struct Pos {
  int y, x, a;
  ll dist;
};

int next_angle(int a, int k){
  if(a == 0){
    if(k==0) return 2;
    if(k==1) return 1;
    if(k==2) return 4;
    if(k==3) return 3;
  }
  if(a == 1){
    if(k==0) return 0;
    if(k==1) return 5;
    if(k==2) return 1;
    if(k==3) return 1;
  }
  if(a == 2){
    if(k==0) return 5;
    if(k==1) return 0;
    if(k==2) return 2;
    if(k==3) return 2;
  }
  if(a == 3){
    if(k==0) return 3;
    if(k==1) return 3;
    if(k==2) return 0;
    if(k==3) return 5;
  }
  if(a == 4){
    if(k==0) return 4;
    if(k==1) return 4;
    if(k==2) return 5;
    if(k==3) return 0;
  }
  if(a == 5){
    if(k==0) return 1;
    if(k==1) return 2;
    if(k==2) return 3;
    if(k==3) return 4;
  }
}

int main(){
  cin >> H >> W;
  cin >> sy >> sx;
  sy--;
  sx--;
  cin >> gy >> gx;
  gy--;
  gx--;
  rep(i,H) cin >> field[i];

  rep(i,1005) rep(j,1005) rep(k,6) dist[i][j][k] = INF;
  queue<Pos> que;
  que.push((Pos){sy,sx,0,0LL});
  while(!que.empty()){
    Pos pos = que.front(); que.pop();
    if(dist[pos.y][pos.x][pos.a] != INF) continue;
    dist[pos.y][pos.x][pos.a] = pos.dist;

    rep(k,4){
      int ny = pos.y + vy[k];
      int nx = pos.x + vx[k];
      if(ny<0 || ny>=H || nx<0 || nx>=W) continue;
      if(field[ny][nx] == '#') continue;
      int next_a = next_angle(pos.a, k);
      if(dist[ny][nx][next_a] != INF) continue;

      que.push((Pos){ny,nx,next_a,pos.dist+1});
    }
  }

  if(dist[gy][gx][0] == INF) cout << -1 << endl;
  else cout << dist[gy][gx][0] << endl;
  
  return 0;
}