#define rep(i, n) for (int i = 0; i < (int)(n); i++) #define ALL(v) v.begin(), v.end() typedef long long ll; #include using namespace std; const ll INF=1LL<<60; struct Edge{ int to; ll w; Edge(int to,ll w) : to(to),w(w) {} }; using Graph=vector>; using pli=pair; template bool chmin(T& a,T b){ if(a>b){ a=b; return true; } return false; } int main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); int h,w,sy,sx,gy,gx; cin>>h>>w>>sy>>sx>>gy>>gx; sy--,sx--,gy--,gx--; vector A(h); rep(i,h) cin>>A[i]; Graph G(6*h*w); rep(i,h){ rep(j,w){ if(A[i][j]=='#') continue; int t=i*w+j; if(j!=w-1 && A[i][j+1]=='.'){ G[t].push_back(Edge(t+1+h*w,1)); G[t+h*w].push_back(Edge(t+1+5*h*w,1)); G[t+2*h*w].push_back(Edge(t+1+2*h*w,1)); G[t+3*h*w].push_back(Edge(t+1,1)); G[t+4*h*w].push_back(Edge(t+1+4*h*w,1)); G[t+5*h*w].push_back(Edge(t+1+3*h*w,1)); G[t+1+h*w].push_back(Edge(t,1)); G[t+1+5*h*w].push_back(Edge(t+h*w,1)); G[t+1+2*h*w].push_back(Edge(t+2*h*w,1)); G[t+1].push_back(Edge(t+3*h*w,1)); G[t+1+4*h*w].push_back(Edge(t+4*h*w,1)); G[t+1+3*h*w].push_back(Edge(t+5*h*w,1)); } if(i!=h-1 && A[i+1][j]=='.'){ G[t].push_back(Edge(t+w+4*h*w,1)); G[t+h*w].push_back(Edge(t+w+h*w,1)); G[t+2*h*w].push_back(Edge(t+w,1)); G[t+3*h*w].push_back(Edge(t+w+3*h*w,1)); G[t+4*h*w].push_back(Edge(t+w+5*h*w,1)); G[t+5*h*w].push_back(Edge(t+w+2*h*w,1)); G[t+w+4*h*w].push_back(Edge(t,1)); G[t+w+h*w].push_back(Edge(t+h*w,1)); G[t+w].push_back(Edge(t+2*h*w,1)); G[t+w+3*h*w].push_back(Edge(t+3*h*w,1)); G[t+w+5*h*w].push_back(Edge(t+4*h*w,1)); G[t+w+2*h*w].push_back(Edge(t+5*h*w,1)); } } } vector dist(6*h*w,INF); int s=sy*w+sx; dist[s]=0; priority_queue,greater> que; que.push({dist[s],s}); while(!que.empty()){ int v=que.top().second; ll d=que.top().first; que.pop(); if(d>dist[v]) continue; for(auto e:G[v]){ if(chmin(dist[e.to],dist[v]+e.w)){ que.push({dist[e.to],e.to}); } } } if(dist[gy*w+gx]==INF) cout<<-1<