#include #include #include #include using namespace std; int main() { int H, W; if (!(cin >> H >> W)) return 0; vector C(H); for (int i = 0; i < H; ++i) cin >> C[i]; vector> dist(H, vector(W, 2e9)); priority_queue>, vector>>, greater>>> pq; dist[0][0] = 0; pq.push({0, {0, 0}}); int dr[] = {0, 0, 1, -1}; int dc[] = {1, -1, 0, 0}; while (!pq.empty()) { int d = pq.top().first; int r = pq.top().second.first; int c = pq.top().second.second; pq.pop(); if (d > dist[r][c]) continue; for (int i = 0; i < 4; ++i) { int nr = r + dr[i]; int nc = c + dc[i]; if (nr >= 0 && nr < H && nc >= 0 && nc < W) { int cost = (C[nr][nc] == '#') ? 2 : 1; if (dist[nr][nc] > d + cost) { dist[nr][nc] = d + cost; pq.push({dist[nr][nc], {nr, nc}}); } } } } if (dist[H - 1][W - 1] == 2e9) cout << -1 << endl; else cout << dist[H - 1][W - 1] << endl; return 0; }