#define _USE_MATH_DEFINES #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 1000000007; // constexpr int MOD = 998244353; constexpr int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1}; constexpr int dy8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dx8[] = {0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T &a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T &a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; // https://github.com/beet-aizu/library/blob/master/tools/dice.cpp int roll(int red, int dir) { int b[]{3, 1, 2, 0}; int v[6][4]={{0,3,5,2}, {0,2,5,3}, {0,1,5,4}, {0,4,5,1}, {1,2,4,3}, {1,3,4,2}}; int fs[6]{}; fs[red] = 1; for(int k=0;k<4;k++){ if(b[k]!=dir) continue; int t=fs[v[k][0]]; fs[v[k][0]]=fs[v[k][1]]; fs[v[k][1]]=fs[v[k][2]]; fs[v[k][2]]=fs[v[k][3]]; fs[v[k][3]]=t; } REP(i, 6) { if (fs[i] == 1) return i; } return -1; } // https://mojacoder.app/users/milkcoffee/contests/mr-contest001/tasks/3 int main() { int h, w, sy, sx, gy, gx; cin >> h >> w >> sy >> sx >> gy >> gx; --sy; --sx; --gy; --gx; vector s(h); REP(i, h) cin >> s[i]; vector dist(h, vector(w, vector(6, -1))); dist[sy][sx][0] = 0; queue> que({{sy, sx, 0}}); while (!que.empty()) { auto [i, j, one] = que.front(); que.pop(); REP(k, 4) { int y = i + dy[k], x = j + dx[k]; if (int nx = roll(one, k); 0 <= y && y < h && 0 <= x && x < w && s[y][x] == '.' && dist[y][x][nx] == -1) { dist[y][x][nx] = dist[i][j][one] + 1; que.emplace(y, x, nx); } } } cout << dist[gy][gx][0] << '\n'; return 0; }