#include using namespace std; #define rep(i,n) for(ll i=0;i<(n);++i) using ll = long long; using pll = pair; constexpr ll INF = (1LL<<60); constexpr ll MOD = (1e9+7); //constexpr ll MOD = (998244353); template bool chmax(T &a,const T &b){if(a bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}return 0;} #if loc||debg||local||debug void dump(){cerr< void dump(T&& h, Ts&&... t){cerr<(t)...);} #else template void dump(T&& h, Ts&&... t){} #endif template istream &operator>>(istream&is,vector&v){for(auto &elemnt:v)is>>elemnt;return is;} template istream &operator>>(istream&is,pair&p){is>>p.first>>p.second;return is;} template ostream &operator<<(ostream& os,vectorconst& v){for(auto const& vi:v)os<vector vec(size_t a){return vector(a);} templateauto vec(size_t a, Ts... ts){return vector(ts...))>(a, vec(ts...));} templatevector _vec(size_t a,T v){return vector(a,v);} templateauto _vec(size_t a, Ts... ts){return vector(ts...))>(a, _vec(ts...));} constexpr ll dx[]={1,0,-1,0,1,1,-1,-1}; constexpr ll dy[]={0,1,0,-1,1,-1,1,-1}; int main(){ int h,w; cin>>h>>w; vector s(h); cin>>s; auto grid_bfs = [&](int sy,int sx){ using T3 = std::tuple; auto chmin = [](auto& a,auto b){if(a>b){a=b;return true;}return false;}; constexpr int inf = 1<<29; constexpr int dx[] = {0,0,1,-1,1,-1,1,-1}; constexpr int dy[] = {1,-1,0,0,1,-1,-1,1}; std::queue que; que.emplace(sy,sx,0); auto dist = std::vector>(h,std::vector(w,inf)); while(!que.empty()){ int y,x,c; std::tie(y,x,c) = que.front(); que.pop(); if(chmin(dist[y][x],c)){ for(int i=0;i<4;++i){ int ny=y+dy[i]; int nx=x+dx[i]; if(ny==-1||nx==-1)continue; if(ny==h||nx==w)continue; // //if(s[ny][nx]!='.')continue; // que.emplace(ny,nx,c+1); } } } return dist; }; auto d0 = grid_bfs(0,0); using T3 = tuple; using T4 = tuple; priority_queue,greater<>> que; que.emplace(0,0,0); auto dist = _vec(h,w,INF); while(!que.empty()){ auto [y,x,c] = que.top(); que.pop(); if(chmin(dist[y][x],c)){ rep(i,4){ auto ny = y+dy[i]; auto nx = x+dx[i]; auto nc = c+1; if(ny==-1||nx==-1)continue; if(ny==h||nx==w)continue; if(s[ny][nx]=='k')nc += d0[ny][nx]; que.emplace(ny,nx,nc); } } } for(auto y:dist)dump(y); cout<<(dist.back().back())<