#define _GLIBCXX_DEBUG #include using namespace std; vector> R = {{-1, 3, 1, 4, 2, -1}, {2, -1, 5, 0, -1, 3}, {4, 0, -1, -1, 5, 1}, {1, 5, -1, -1, 0, 4}, {3, -1, 0, 5, -1, 2}, {-1, 2, 4, 1, 3, -1}}; int main(){ int H, W; cin >> H >> W; int sy, sx; cin >> sy >> sx; sy--; sx--; int gy, gx; cin >> gy >> gx; gy--; gx--; vector> A(H, vector(W)); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ cin >> A[i][j]; } } queue> Q; Q.push(make_tuple(sy, sx, 0, 1)); vector>>> d(H, vector>>(W, vector>(6, vector(6, -1)))); d[sy][sx][0][1] = 0; int ans = -1; while (!Q.empty()){ int y = get<0>(Q.front()); int x = get<1>(Q.front()); int t = get<2>(Q.front()); int f = get<3>(Q.front()); Q.pop(); if (y == gy && x == gx && t == 0){ ans = d[y][x][t][f]; break; } int r = R[t][f]; if (y < H - 1){ if (A[y + 1][x] == '.' && d[y + 1][x][5 - f][t] == -1){ d[y + 1][x][5 - f][t] = d[y][x][t][f] + 1; Q.push(make_tuple(y + 1, x, 5 - f, t)); } } if (y > 0){ if (A[y - 1][x] == '.' && d[y - 1][x][f][5 - t] == -1){ d[y - 1][x][f][5 - t] = d[y][x][t][f] + 1; Q.push(make_tuple(y - 1, x, f, 5 - t)); } } if (x < W - 1){ if (A[y][x + 1] == '.' && d[y][x + 1][5 - r][f] == -1){ d[y][x + 1][5 - r][f] = d[y][x][t][f] + 1; Q.push(make_tuple(y, x + 1, 5 - r, f)); } } if (x > 0){ if (A[y][x - 1] == '.' && d[y][x - 1][r][f] == -1){ d[y][x - 1][r][f] = d[y][x][t][f] + 1; Q.push(make_tuple(y, x - 1, r, f)); } } } cout << ans << endl; }