#include #ifdef LOCAL #include #else #define debug(...) void(0) #endif using namespace std; typedef long long ll; #define all(x) begin(x), end(x) constexpr int INF = (1 << 30) - 1; constexpr long long IINF = (1LL << 60) - 1; template istream& operator>>(istream& is, vector& v) { for (auto& x : v) is >> x; return is; } template ostream& operator<<(ostream& os, const vector& v) { auto sep = ""; for (const auto& x : v) os << exchange(sep, " ") << x; return os; } template bool chmin(T& x, U&& y) { return y < x and (x = forward(y), true); } template bool chmax(T& x, U&& y) { return x < y and (x = forward(y), true); } template void mkuni(vector& v) { sort(begin(v), end(v)); v.erase(unique(begin(v), end(v)), end(v)); } template int lwb(const vector& v, const T& x) { return lower_bound(begin(v), end(v), x) - begin(v); } constexpr int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1}, dy[8] = {0, 1, 0, -1, 1, -1, 1, -1}; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int H, W; cin >> H >> W; vector S(H); cin >> S; vector ok(H, vector(W, true)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (S[i][j] != '#') continue; ok[i][j] = false; for (int k = 0; k < 8; k++) { int nx = i + dx[k], ny = j + dy[k]; if (nx < 0 or H <= nx or ny < 0 or W <= ny) continue; ok[nx][ny] = false; } } } vector dp(H + 2, vector(W + 2, INF)); deque> que; for (int i = 0; i < H; i++) { dp[i + 1][0] = 0; que.emplace_back(i, -1); } for (int j = 0; j < W; j++) { dp[H + 1][j + 1] = 0; que.emplace_back(H, j); } while (not que.empty()) { auto [x, y] = que.front(); que.pop_front(); if (x == -1 and y == -1) continue; if (x == H and y == W) continue; int val = dp[x + 1][y + 1]; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (nx < -1 or H < nx or ny < -1 or W < ny) continue; if (nx == -1 or ny == W or (nx < H and -1 < ny and not ok[nx][ny])) { if (chmin(dp[nx + 1][ny + 1], val)) que.emplace_front(nx, ny); } } for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { int cx = x + i, cy = y + j; if (cx < 0 or H <= cx or cy < 0 or W <= cy) continue; if (cx < 3 and cy < 3) continue; if (H - 3 <= cx and W - 3 <= cy) continue; bool f = false; for (int k = 0; k < 8; k++) { int nx = cx + dx[k], ny = cy + dy[k]; if (nx < 0 or H <= nx or ny < 0 or W <= ny) continue; if (abs(nx - x) + abs(ny - y) <= 1) f = true; } if (not f) continue; if (chmin(dp[cx + 1][cy + 1], val + 1)) que.emplace_back(cx, cy); for (int k = 0; k < 8; k++) { int nx = cx + dx[k], ny = cy + dy[k]; if (nx < 0 or H <= nx or ny < 0 or W <= ny) continue; if (chmin(dp[nx + 1][ny + 1], val + 1)) que.emplace_back(nx, ny); } } } } int ans = INF; for (int i = 0; i < H; i++) chmin(ans, dp[i + 1][W + 1]); for (int j = 0; j < W; j++) chmin(ans, dp[0][j + 1]); cout << ans << '\n'; return 0; }