1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<bits/stdc++.h> #define x first #define y second #define ok puts("ok"); using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const double PI = acos(-1.0); const int INF=0x3f3f3f3f; const ll LINF=0x3f3f3f3f3f3f3f3f; const int N=2e5+9; const int shift=1e3+9; const double Eps=1e-7;
int cnt, n, m, dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}, vis[N], ban[N], sx, sy, gx, gy, d, dis[N], b[N]; string g[N]; vector<pii> v;
inline bool check(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; }
inline int id(pii t) { return t.x * m + t.y; }
inline int id(int x, int y) { return x * m + y; }
void banbfs() { queue<pii> que; for(int i = 0; i < v.size(); i++) { que.push(pii(v[i].x, v[i].y)); vis[id(v[i])] = 1; b[id(v[i])] = d; } while(que.size()) { pii u = que.front(); que.pop(); if(b[id(u)] == 0) break; for(int i = 0; i < 4; i++) { int nx = u.x + dx[i], ny = u.y + dy[i]; if(check(nx, ny) && !vis[id(nx, ny)]) { vis[id(nx, ny)] = 1; ban[id(nx, ny)] = 1; b[id(nx, ny)] = b[id(u)] - 1; que.push(pii(nx, ny)); } } } }
void bfs() { banbfs(); queue<pii> que; if(!ban[id(sx, sy)]) que.push(pii(sx, sy)); memset(dis, -1, sizeof dis); dis[id(pii(sx, sy))] = 0; vis[id(sx, sy)] = 1; while(que.size()) { pii u = que.front(); que.pop(); if(u.x == gx && u.y == gy) { break; } for(int i = 0; i < 4; i++) { int nx = u.x + dx[i], ny = u.y + dy[i]; if(check(nx, ny) && !vis[id(nx, ny)] && !ban[id(nx, ny)]) { que.push(pii(nx, ny)); vis[id(nx, ny)] = 1; dis[id(pii(nx, ny))] = dis[id(u)] + 1; } } } printf("%d\n", dis[id(pii(gx, gy))]); }
int main(void) { if(fopen("in", "r")!=NULL) {freopen("in", "r", stdin); freopen("out", "w", stdout);} while(cin >> n >> m >> d) { for(int i = 0; i < n; i++) cin >> g[i]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { if(g[i][j] == 'S') sx = i, sy = j; else if(g[i][j] == 'M') v.push_back(pii(i, j)); else if(g[i][j] == 'F') gx = i, gy = j; } bfs(); }
return 0; }
|