#include #include using namespace std; using namespace atcoder; typedef int64_t lint; #define rep(i, n) for(int i=0; i; using vvi = vector>; template inline void vin(vector& v) { rep(i, v.size()) cin >> v.at(i); } template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } template inline void drop(T x) { cout << x << endl; exit(0); } template void vout(vector v) { rep(i, v.size()) { cout << v.at(i) << ' '; } cout << endl; } constexpr lint LINF = LLONG_MAX/2; using pint = pair; using vp = vector; template map coord_comp(set s) { int a = 0; map m; for (auto u : s) m[u] = ++a; return m; } template inline void vvout(vector v) { rep(i, v.size()) { rep(j, v[i].size()) { list(v[i][j].first) list(v[i][j].second) } cout << endl; } } vector> G; void dijkstra(lint start, vector &dist) { lint a=0, b=0, x, y, N = G.size(); dist.resize(N, LINF); dist[start] = 0; priority_queue, greater> PQ; PQ.push(make_pair(0, start)); while (!PQ.empty()) { tie(x, a) = PQ.top(); PQ.pop(); if (dist[a] < x) continue; for (auto p : G[a]) { tie(y, b) = p; if (chmin(dist[b], x+y)) PQ.push(make_pair(x+y, b)); } } } int main() { lint H, W; cin >> H >> W; std::vector v(H); vin(v); lint a=0, b=0, c=0, x, y, z; set s; s.insert({-1, W+1}); s.insert({H+1, -1}); rep(i, H) { rep(j, W) { if (v[i][j] == '#') s.insert({i, j}); } } map m = coord_comp(s); G.resize(m.size()+1); x = m[{-1, W+1}]; for (auto p : s) { if (x == m[p]) continue; tie(c, z) = p; G[x].pb({min(c/3, (W-z-1)/3), m[p]}); } x = m[{H+1, -1}]; for (auto p : s) { if (x == m[p]) continue; tie(c, z) = p; G[m[p]].pb({min((H-c-1)/3, z/3), x}); } for (auto p : s) { x = m[p]; tie(c, z) = p; if (c == -1 || z == -1) continue; for (auto q : s) { y = m[q]; if (x == y) continue; tie(a, b) = q; if (a == -1 || b == -1) continue; if (abs(a-c) == abs(z-b)) { G[x].pb({max(abs(a-c)/3, abs(z-b)/3), y}); } else { G[x].pb({max((abs(a-c)-1)/3, (abs(z-b)-1)/3), y}); } } } vi dist; dijkstra(m[{-1, W+1}], dist); std::cout << dist[m[{H+1, -1}]] << '\n'; }