#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int n, s, dist[N][N];
char mat[N][N];
pair<int, int> bst[N][N];
bool valid(int x, int y){
return (x >= 0 and x < n and y >= 0 and y < n and mat[x][y] != 'T');
}
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
void bfs(){
memset(dist, 31, sizeof dist);
queue<pair<int, int>> q;
for (int i = 0; i < n; i ++){
for (int j = 0; j < n; j ++){
if (mat[i][j] == 'H'){
dist[i][j] = 0;
q.push({i, j});
}
}
}
while (!q.empty()){
auto [x, y] = q.front();
q.pop();
for (int i = 0; i < 4; i ++){
int nx = x + dx[i];
int ny = y + dy[i];
if (!valid(nx, ny) or dist[nx][ny] <= dist[x][y] + 1)
continue;
if (mat[nx][ny] == 'D') continue;
dist[nx][ny] = dist[x][y] + 1;
q.push({nx, ny});
}
}
}
void dijkstra(){
int sx, sy;
for (int x = 0; x < n; x ++){
for (int y = 0; y < n; y ++){
bst[x][y] = {1e9, 0};
if (mat[x][y] == 'M')
sx = x, sy = y;
}
}
set<pair<pair<int, int>, pair<int, int>>> st;
st.insert({{0 - dist[sx][sy], 0}, {sx, sy}});
bst[sx][sy] = {0 - dist[sx][sy], 0};
int ans = dist[sx][sy];
while (!st.empty()){
auto [P, Q] = *st.begin();
auto [val, steps] = P;
auto [x, y] = Q;
st.erase(st.begin());
ans = min(ans, -val);
for (int i = 0; i < 4; i ++){
int nx = x + dx[i];
int ny = y + dy[i];
if (!valid(nx, ny) or mat[nx][ny] == 'H') continue;
int nd = ((steps + s) / s) - dist[nx][ny];
if (bst[nx][ny].first > nd){
st.erase({bst[nx][ny], {nx, ny}});
bst[nx][ny] = {nd, steps + 1};
st.insert({bst[nx][ny], {nx, ny}});
}
if (mat[nx][ny] == 'D'){
if (ans <= 0) ans = -1;
cout << ans << endl;
return ;
}
}
}
}
int main(){
cin >> n >> s;
for (int i = 0; i < n; i ++)
for (int j = 0; j < n; j ++)
cin >> mat[i][j];
bfs();
dijkstra();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |