#include using namespace std; #define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++) #define rrep(i, a, b) for (int i = (int)(a); i > (int)(b); i--) #define ll long long #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define PQ priority_queue, greater> #define PQ_g priority_queue, vector>, greater>> #define chmin(a, b) a = min(a, b) #define chmax(a, b) a = max(a, b) const int d4[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int d8[8][2] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; void Yes(bool b) {cout << (b ? "Yes" : "No") << endl;} int main() { int h, w; cin >> h >> w; vector C(h); rep(i, 0, h) cin >> C[i]; queue> Q; vector> dist_s(h, vector (w, 1 << 30)); vector> dist_g(h, vector (w, 1 << 30)); vector> visited_s(h, vector (w)); vector> visited_g(h, vector (w)); auto can_go = [&](int x, int y) -> bool{ return 0 <= x && x < h && 0 <= y && y < w && C[x][y] != '#'; }; Q.push(make_pair(0, 0)); dist_s[0][0] = 0; while (!Q.empty()) { int posx = Q.front().first; int posy = Q.front().second; Q.pop(); if (visited_s[posx][posy]) continue; visited_s[posx][posy] = true; const int d2[2][2] = {{0, 1}, {1, 0}}; for (auto &to: d2) { int next_x = posx + to[0]; int next_y = posy + to[1]; if (can_go(next_x, next_y) && !visited_s[next_x][next_y]) { dist_s[next_x][next_y] = min(dist_s[next_x][next_y], dist_s[posx][posy] + 1); Q.push(make_pair(next_x, next_y)); } } } Q.push(make_pair(h - 1, w - 1)); dist_g[h - 1][w - 1] = 0; while (!Q.empty()) { int posx = Q.front().first; int posy = Q.front().second; Q.pop(); if (visited_g[posx][posy]) continue; visited_g[posx][posy] = true; const int d2[2][2] = {{0, -1}, {-1, 0}}; for (auto &to: d2) { int next_x = posx + to[0]; int next_y = posy + to[1]; if (can_go(next_x, next_y) && !visited_g[next_x][next_y]) { dist_g[next_x][next_y] = min(dist_g[next_x][next_y], dist_g[posx][posy] + 1); Q.push(make_pair(next_x, next_y)); } } } if (visited_s[h - 1][w - 1]) { cout << dist_s[h - 1][w - 1] << endl; } else { bool flg = false; rep(i, 0, h - 1) { bool have_s = false; rep(j, 0, w) { if (visited_s[i][j]) have_s = true; if (visited_g[i + 1][j] && have_s) { flg = true; break; } } if (flg) break; } rep(j, 0, w - 1) { bool have_s = false; rep(i, 0, h) { if (visited_s[i][j]) have_s = true; if (visited_g[i][j + 1] && have_s) { flg = true; break; } } if (flg) break; } cout << (flg ? (h + w - 1) : (h + w)) << endl; } }