#include using namespace std; const int MAX_NODES = 16000005; int dist_arr[MAX_NODES]; int q[MAX_NODES]; bool can_enter[MAX_NODES]; int main() { cin.tie(0)->sync_with_stdio(0); int H, W; if (!(cin >> H >> W)) return 0; int R = 2 * H - 1; int C = 2 * W - 1; for (int i = 0; i < H; ++i) { string s; cin >> s; for (int j = 0; j < W; ++j) { if (s[j] != '#') { can_enter[(i * 2) * C + (j * 2)] = true; } } } for (int y = 0; y < R; ++y) { for (int x = 0; x < C; ++x) { if ((y & 1) || (x & 1)) { can_enter[y * C + x] = true; } dist_arr[y * C + x] = -1; } } int head = 0, tail = 0; q[tail++] = 0; dist_arr[0] = 0; int target = (R - 1) * C + (C - 1); while (head < tail) { int u = q[head++]; if (u == target) { cout << dist_arr[u] << '\n'; return 0; } int y = u / C; int x = u % C; int d = dist_arr[u] + 1; auto push = [&](int v) { if (can_enter[v] && dist_arr[v] == -1) { dist_arr[v] = d; q[tail++] = v; } }; if (y > 0) push(u - C); if (y + 1 < R) push(u + C); if (x > 0) push(u - 1); if (x + 1 < C) push(u + 1); if (!(x & 1)) { if (x > 1) push(u - 2); if (x + 2 < C) push(u + 2); } if (!(y & 1)) { if (y > 1) push(u - 2 * C); if (y + 2 < R) push(u + 2 * C); } } cout << -1 << '\n'; return 0; }