import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } enum INF = 10^^9; void main() { try { for (; ; ) { const M = readInt; const N = readInt; auto S = new string[M]; foreach (x; 0 .. M) { S[x] = readToken; } auto a = new char[][](M, N); foreach (x; 0 .. M) { a[x][] = '.'; } foreach (x; 0 .. M) foreach (y; 0 .. N) if (S[x][y] == '#') { foreach (dx; -1 .. +1 + 1) foreach (dy; -1 .. +1 + 1) { const xx = x + dx; const yy = y + dy; if (0 <= xx && xx < M && 0 <= yy && yy < N) { a[xx][yy] = '#'; } } } foreach (x; 0 .. M) foreach (y; 0 .. N) { if (x == 0 || x == M - 1 || y == 0 || y == N - 1) { a[x][y] = '#'; } if ((x < 2 && y < 2) || (x >= M - 2 && y >= N - 2)) { a[x][y] = '.'; } } debug { foreach (x; 0 .. M) { writeln(a[x]); } } auto transUp = new int[1 << 9]; auto transRight = new int[1 << 9]; foreach (p; 0 .. 1 << 9) { transUp[p] = p >> 3; int pp; foreach (dx; 0 .. 3) pp &= ~(1 << (dx * 3)); transRight[p] = pp >> 1; } auto dp = new int[][][](M, N, 1 << 9); foreach (x; 0 .. M) foreach (y; 0 .. N) { dp[x][y][] = INF; } dp[M - 1][0][0] = 0; foreach_reverse (x; 0 .. M) foreach (y; 0 .. N) { int has; foreach (dx; 0 .. 3) foreach (dy; 0 .. 3) { const xx = x - dx; const yy = y + dy; if (xx >= 0 && yy < N && a[xx][yy] == '#') { has |= 1 << (dx * 3 + dy); } } foreach (p; 0 .. 1 << 9) if (dp[x][y][p] < INF) { const pp = has | p; if (x - 1 >= 0) { if (pp >> 3 & 1) { chmin(dp[x - 1][y][transUp[p]], dp[x][y][p]); } chmin(dp[x - 1][y][$ - 1], dp[x][y][p] + 1); } if (y + 1 < N) { if (pp >> 1 & 1) { chmin(dp[x][y + 1][transUp[p]], dp[x][y][p]); } chmin(dp[x][y + 1][$ - 1], dp[x][y][p] + 1); } } } const ans = dp[0][N - 1].minElement; writeln(ans); } } catch (EOFException e) { } }