#include int main() { using namespace std; cin.tie(nullptr)->sync_with_stdio(false); int h, w; cin >> h >> w; int si, sj; cin >> si >> sj; --si, --sj; int ti, tj; cin >> ti >> tj; --ti, --tj; vector s(h); for (auto&& e : s) cin >> e; constexpr array di{1, 0, -1, 0}; constexpr array dj{0, 1, 0, -1}; array, 6> get_nk; get_nk[0] = {1, 2, 3, 4}; get_nk[1] = {5, 1, 0, 1}; get_nk[2] = {2, 5, 2, 0}; get_nk[3] = {0, 3, 5, 3}; get_nk[4] = {4, 0, 4, 5}; get_nk[5] = {3, 4, 1, 2}; vector dist(h, vector>(w)); for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) dist[i][j].fill(-1); vector> que{{si, sj, 0}}; dist[si][sj][0] = 0; for (int z = 0; z < int(size(que)); ++z) { auto [i, j, k] = que[z]; if (i == ti and j == tj and k == 0) { cout << dist[i][j][k] << '\n'; exit(0); } for (int d : {0, 1, 2, 3}) { int ni = i + di[d]; int nj = j + dj[d]; if (ni < 0 or ni >= h or nj < 0 or nj >= w or s[ni][nj] == '#') continue; int nk = get_nk[k][d]; if (dist[ni][nj][nk] == -1) { dist[ni][nj][nk] = dist[i][j][k] + 1; que.emplace_back(ni, nj, nk); } } } cout << "-1\n"; }