#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int,long long>;
using ld = long double;
#define int long long
#define el cout << '\n'
#define fi first
#define se second
#define pb push_back
#define all(x) x.begin(), x.end()
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FOD(i, a, b) for (int i = (a); i >= (b); i--)
#define REP(i, n) for (int i = 0; i < (n); i++)
template <class T1, class T2>bool chmax(T1 &a, T2 b){if (a < b) {a = b; return true;}return false;}
template <class T1, class T2>bool chmin(T1 &a, T2 b){if (a > b) {a = b; return true;}return false;}
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const ll mod = 1e9 + 7;
void solve(){
int n, k;
cin >> n >> k;
string s[n];
REP(i, n){
cin >> s[i];
}
pii start, des;
vector<vector<int>> dis(n, vector<int> (n ,1e9));
queue<pii> q;
REP(i, n){
REP(j, n){
if (s[i][j] == 'M'){
start = {i, j};
}
if (s[i][j] == 'D'){
des = {i, j};
}
if (s[i][j] == 'H'){
q.push({i, j});
dis[i][j] = 0;
}
}
}
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
while(q.size()){
auto [x, y] = q.front();
q.pop();
for (int i = 0; i < 4; i++){
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= n) continue;
if (s[a][b] == 'T' || s[a][b] == 'D') continue;
if (dis[x][y] + 1 < dis[a][b]){
dis[a][b] = dis[x][y] + 1;
q.push({a, b});
}
}
}
// REP(i, n){
// REP(j, n){
// cerr << dis[i][j] << " ";
// }
// cerr << '\n';
// }
// cerr << '\n';
auto check = [&](int m){
queue<pii> que;
que.push(start);
vector<vector<int>> dis2(n, vector<int> (n, 1e9));
dis2[start.fi][start.se] = 0;
while(que.size()){
auto [x, y] = que.front();
que.pop();
if (x == des.fi && y == des.se) break;
for (int i = 0; i < 4; i++){
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= n) continue;
if (s[a][b] == 'T') continue;
int cur = dis2[x][y];
if ((cur + 1) / k < dis[a][b] - m && cur + 1 < dis2[a][b]){
dis2[a][b] = cur + 1;
que.push({a, b});
}
}
}
// REP(i, n){
// REP(j, n){
// cerr << dis2[i][j] << " ";
// }
// cerr << '\n';
// }
return dis2[des.fi][des.se] != 1e9;
};
if (!check(0)){
cout << -1;
return;
}
int l = -1, r = mx + 1;
while(r - l > 1){
int mid = (l + r) / 2;
if (check(mid)) l = mid;
else r = mid;
}
cout << l;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tests = 1;
//cin >> tests;
for (int _ = 1; _ <= tests; _++){
cerr << "- Case #" << _ << ": \n";
solve();
el;
}
return 0;
}
Compilation message
mecho.cpp: In function 'void solve()':
mecho.cpp:104:19: error: 'mx' was not declared in this scope; did you mean 'dx'?
104 | int l = -1, r = mx + 1;
| ^~
| dx