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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
| #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 800 + 5;
template <typename _Tp> void read(_Tp &a, char c = 0) { for(c = getchar(); !isdigit(c); c = getchar()); for(a = 0; isdigit(c); a = a * 10 + c - '0', c = getchar()); }
int T, m, n; char a[N][N];
struct pos { int x, y; pos() {} pos(int _x, int _y): x(_x), y(_y) {} };
int d[4][2] = { 0, 1, 0, -1, 1, 0, -1, 0 }; vector<pos> Z;
bool check(const pos &p, int op, int t) { int x = p.x; int y = p.y; if(op == 0 && a[x][y] == 'M') return false; if(op == 1 && a[x][y] == 'G') return false; if(a[x][y] == 'X') return false; if(x < 1 || x > n || y < 1 || y > m) return false; for(int i = 0; i < 2; i++) { pos &Zp = Z[i]; int _x = Zp.x; int _y = Zp.y; int dis = abs(x - _x) + abs(y - _y); if(dis <= 2 * t) return false; } return true; }
bool check_ghost(const pos &p, int op, int t) { int x = p.x; int y = p.y; for(int i = 0; i < 2; i++) { pos &Zp = Z[i]; int _x = Zp.x; int _y = Zp.y; int dis = abs(x - _x) + abs(y - _y); if(dis <= 2 * t) return false; } return true; }
void print_map() { for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { printf("%c", a[i][j]); } puts(""); } }
bool bfs(queue<pos> &q, int op, int s, int t) { queue<pos> tmp; for(int i = 1; i <= s; i++) { while(!q.empty()) { pos p = q.front(); q.pop(); if(!check_ghost(p, op, t)) { continue; } for(int j = 0; j < 4; j++) { pos np; np.x = p.x + d[j][0]; np.y = p.y + d[j][1]; if(check(np, op, t)) { if(op == 0) { if(a[np.x][np.y] == 'G') { return true; } else a[np.x][np.y] = 'M'; } if(op == 1) { if(a[np.x][np.y] == 'M') { return true; } else a[np.x][np.y] = 'G'; } tmp.push(np); } } } q = tmp; while(!tmp.empty()) tmp.pop(); } return false; }
void init() { Z.clear(); memset(a, 0, sizeof a); }
char str[N];
int main() { read(T); while(T--) { init(); queue<pos> M, G; read(n), read(m); for(int i = 1; i <= n; i++) { scanf("%s", str + 1); for(int j = 1; j <= m; j++) { char c = str[j]; a[i][j] = c; if(c == 'M') M.push(pos(i, j)); if(c == 'G') G.push(pos(i, j)); if(c == 'Z') Z.push_back(pos(i, j)); } } int t = 0; bool f = 0; while(!(M.empty() && G.empty())) { t++; if(bfs(M, 0, 3, t)) { f = 1; break; } if(bfs(G, 1, 1, t)) { f = 1; break; } } printf("%d\n", f ? t : -1); } return 0; }
|