#include #include #include #include #include #include using namespace std; using ll = long long; #define rep(i, n) for (int i = 0; i < n; ++i) int main() { ll h, w; cin >> h >> w; vector s(h); rep(i, h) cin >> s[i]; s[0][0] = '.'; s[h-1][w-1] = '.'; ll H = h * 2 - 1; ll W = w * 2 - 1; auto itop = [&](ll i) { return pair{i / W, i % W}; }; auto ptoi = [&](pair p) { return p.first * W + p.second; }; vector> g(H * W); rep(i, h) { rep(j, w) { if(s[i][j] == '.') { if(j < w-1 && s[i][j+1] == '.') { g[ptoi({i * 2, j * 2})].emplace_back(ptoi({i * 2, j * 2 + 2})); } if(i < h-1 && s[i+1][j] == '.') { g[ptoi({i * 2, j * 2})].emplace_back(ptoi({i * 2 + 2, j * 2})); } if(i < h-1) { g[ptoi({i * 2, j * 2})].emplace_back(ptoi({i * 2 + 1, j * 2})); } if(j < w-1) { g[ptoi({i * 2, j * 2})].emplace_back(ptoi({i * 2, j * 2 + 1})); } } } } rep(i, h) { rep(j, w) { if(i != h-1) { g[ptoi({i * 2 + 1, j * 2})].emplace_back(ptoi({i * 2 + 2, j * 2})); } if(j != w-1) { g[ptoi({i * 2, j * 2 + 1})].emplace_back(ptoi({i * 2, j * 2 + 2})); } if(i != h-1 && j != w-1) { g[ptoi({i * 2 + 1, j * 2})].emplace_back(ptoi({i * 2 + 1, j * 2 + 1})); g[ptoi({i * 2 + 1, j * 2})].emplace_back(ptoi({i * 2 + 1, j * 2 + 2})); g[ptoi({i * 2, j * 2 + 1})].emplace_back(ptoi({i * 2 + 1, j * 2 + 1})); g[ptoi({i * 2, j * 2 + 1})].emplace_back(ptoi({i * 2 + 2, j * 2 + 1})); g[ptoi({i * 2 + 1, j * 2 + 1})].emplace_back(ptoi({i * 2 + 2, j * 2 + 1})); g[ptoi({i * 2 + 1, j * 2 + 1})].emplace_back(ptoi({i * 2 + 1, j * 2 + 2})); } } } const ll INF = 1LL<<60; vector> dist(H, vector(W, INF)); dist[0][0] = 0; queue q; q.emplace(0); while(!q.empty()) { auto v = q.front(); q.pop(); auto vp = itop(v); // cout << vp.first <<" " << vp.second << endl; auto cost = dist[vp.first][vp.second]; cost++; for(auto c : g[v]) { auto p = itop(c); // cout << p.first << " " << p.second << endl; if(dist[p.first][p.second] > cost) { q.emplace(c); dist[p.first][p.second] = cost; } } // rep(i, H) { // rep(j, W) { // cout << dist[i][j] << " "; // } // cout << endl; // } // cout << "---" << endl; } cout << (dist[H-1][W-1] == INF ? -1 : dist[H-1][W-1]) << endl; }