#pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include #define var auto using namespace std; using ll = long long; int main() { cin.tie(0); ios::sync_with_stdio(false); int h, w; cin >> h >> w; string map; for (size_t i = 0; i < h; i++) { string tmp; cin >> tmp; map += tmp; } vector dists(h * w); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { var id = i * w + j; dists[id] = i + j; } vector> graph(h * w, vector()); for (int i = 0; i < h - 1; i++) for (int j = 0; j < w; j++) { var id = i * w + j; graph[id].push_back(id + w); graph[id + w].push_back(id); } for (int i = 0; i < h; i++) for (int j = 0; j < w - 1; j++) { var id = i * w + j; graph[id].push_back(id + 1); graph[id + 1].push_back(id); } vector shortest(graph.size(), 1L << 60); priority_queue, vector>, greater>> pqueue{}; pqueue.push(make_pair(0, 0)); while (!pqueue.empty()) { var item = pqueue.top(); pqueue.pop(); if (shortest[item.second] != 1L << 60) continue; shortest[item.second] = item.first; for(var&& elem : graph[item.second]) { if (shortest[elem] != 1L << 60) continue; pqueue.push(make_pair(item.first + 1 + (map[elem] == 'k' ? dists[elem] : 0), elem)); } } cout << shortest[h * w - 1] << endl; return 0; }