#include #include #include #include using namespace std; const int INF = 1e9; int main() { int H, W; cin >> H >> W; vector C(H); for (int i = 0; i < H; ++i) cin >> C[i]; vector> dist(H, vector(W, INF)); deque> dq; dist[0][0] = 0; dq.push_back({0, 0}); int dy[] = {1, -1, 0, 0}; int dx[] = {0, 0, 1, -1}; while (!dq.empty()) { pair cur = dq.front(); dq.pop_front(); int y = cur.first; int x = cur.second; for (int i = 0; i < 4; ++i) { int ny = y + dy[i]; int nx = x + dx[i]; if (ny >= 0 && ny < H && nx >= 0 && nx < W) { int cost = (C[ny][nx] == '#' ? 2 : 1); if (dist[ny][nx] > dist[y][x] + cost) { dist[ny][nx] = dist[y][x] + cost; if (cost == 1) dq.push_front({ny, nx}); else dq.push_back({ny, nx}); } } } } int res = dist[H - 1][W - 1]; cout << (res == INF ? -1 : res) << endl; return 0; }