#include #include #include using namespace atcoder; using mint = modint998244353; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000001 struct dice{ /* Top,Left, Front,Back, Right,Bottom */ vector number = {1,2,3,4,5,6}; vector> states; void findStates(){ states.clear(); rep(i,4){ rep(j,4){ states.push_back(number); rotateClockwise(1); } rotateFront(1); } rotateLeft(1); rep(i,4){ states.push_back(number); rotateClockwise(1); } rotateLeft(2); rep(i,4){ states.push_back(number); rotateClockwise(1); } rotateLeft(1); } void set(vector numbers){ number = numbers; } void rotateFront(int n = 1){ n = (n%4+4)%4; rep(i,n){ int t = top(); top() = back(); back() = bottom(); bottom() = front(); front() = t; } } void rotateLeft(int n = 1){ n = (n%4+4)%4; rep(i,n){ int t = top(); top() = right(); right() = bottom(); bottom() = left(); left() = t; } } void rotateClockwise(int n = 1){ n = (n%4+4)%4; rep(i,n){ int t = front(); front() = right(); right() = back(); back() = left(); left() = t; } } int& top(){ return number[0]; } int& bottom(){ return number[5]; } int& front(){ return number[2]; } int& back(){ return number[3]; } int& left(){ return number[1]; } int& right(){ return number[4]; } const int& top()const{ return number[0]; } const int& bottom()const{ return number[5]; } const int& front()const{ return number[2]; } const int& back()const{ return number[3]; } const int& left()const{ return number[1]; } const int& right()const{ return number[4]; } }; int dis[1005][1005][6]; int main(){ int H,W; cin>>H>>W; int sx,sy,gx,gy; cin>>sy>>sx>>gy>>gx; sx--;sy--;gx--;gy--; vector S(H); rep(i,H){ cin>>S[i]; } rep(i,H){ rep(j,W){ rep(k,6){ dis[i][j][k] = Inf; } } } dis[sy][sx][0] = 0; queue> Q; Q.push({sy,sx,0}); vector dy = {0,-1,0,1},dx = {1,0,-1,0}; while(Q.size()>0){ int y = Q.front()[0]; int x = Q.front()[1]; int d = Q.front()[2]; Q.pop(); rep(i,4){ int yy = y + dy[i],xx = x+dx[i]; if(yy<0||yy>=H||xx<0||xx>=W)continue; if(S[yy][xx]=='#')continue; vector t(6,1); t[d] = 0; dice D; D.set(t); if(i==0)D.rotateFront(1); if(i==1)D.rotateLeft(1); if(i==2)D.rotateFront(3); if(i==3)D.rotateLeft(3); int dd; rep(j,6){ if(D.number[j]==0){ dd = j; break; } } if(dis[yy][xx][dd]!=Inf)continue; dis[yy][xx][dd] = dis[y][x][d] + 1; Q.push({yy,xx,dd}); } } int ans = dis[gy][gx][0]; if(ans==Inf)ans = -1; cout<