#include #include #include #include using namespace std; const long long INF = 1e18; int main() { int H, W; cin >> H >> W; vector grid(H); for (int i = 0; i < H; ++i) { cin >> grid[i]; } vector> dist(H, vector(W, INF)); 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()) { long long 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 = (grid[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] == INF) { cout << -1 << endl; } else { cout << dist[H - 1][W - 1] << endl; } return 0; }