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
| #include <bits/stdc++.h>
#ifdef ORZXKR #include <debug.h> #else #define debug(...) 114514 #endif
using namespace std;
const int kMaxN = 805, kInf = 0x3f3f3f3f; const pair<int, int> dir[] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
struct Node { int x, y, step; Node() {} Node(int _x, int _y, int _step) : x(_x), y(_y), step(_step) {} ~Node() {} };
int T, n, m, ct; int xx, xy, yx, yy; int a[kMaxN][kMaxN], step[2][kMaxN][kMaxN]; string s; char c[kMaxN][kMaxN]; pair<int, int> z[2]; queue<Node> q1, q2;
void init() { while (!q1.empty()) q1.pop(); while (!q2.empty()) q2.pop(); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { step[0][i][j] = step[1][i][j] = kInf; } } }
int get(int x, int y, int p) { return abs(x - z[p].first) + abs(y - z[p].second); }
bool check(int x, int y, int p) { if (x < 1 || x > n || y < 1 || y > m || a[x][y] == 2) return 0; if (get(x, y, 0) <= p * 2 || get(x, y, 1) <= p * 2) return 0; return 1; }
int bfs() { init(); q1.emplace(Node(xx, xy, 0)), q2.emplace(Node(yx, yy, 0)); step[0][xx][xy] = step[1][yx][yy] = 0; int st = 0; while (!q1.empty() || !q2.empty()) { int x, y; ++st; if (!q1.empty()) { for (int k = 0; k < 3; ++k) { int m3, n3; int kk = q1.size(); for (int hbq = 1; hbq <= kk; ++hbq) { auto p1 = q1.front(); q1.pop(); x = p1.x, y = p1.y; if (!check(x, y, st)) continue ; for (auto d3 : dir) { m3 = x + d3.first, n3 = y + d3.second; if (!check(m3, n3, st) || step[0][m3][n3] != kInf) continue ; q1.emplace(Node(m3, n3, st)), step[0][m3][n3] = st; if (step[1][m3][n3] == kInf) continue ; return st; } }
}
}
if (!q2.empty()) { int kk = q2.size(); for (int hbq = 1; hbq <= kk; ++hbq) { auto p2 = q2.front(); q2.pop(); x = p2.x, y = p2.y; if (!check(x, y, st)) continue ; for (auto d : dir) { int tx = x + d.first, ty = y + d.second; if (!check(tx, ty, st) || step[1][tx][ty] != kInf) continue ; q2.emplace(Node(tx, ty, st)), step[1][tx][ty] = st; if (step[0][tx][ty] == kInf) continue ; return st; } }
} } debug(step[0][5][3]); return -1; }
int main() { scanf("%d", &T); while (T--) { ct = 0; scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%s", c[i] + 1); } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (c[i][j] == '.') { a[i][j] = 1; } else if (c[i][j] == 'X') { a[i][j] = 2; } else if (c[i][j] == 'M') { a[i][j] = 1, xx = i, xy = j; } else if (c[i][j] == 'G') { a[i][j] = 1, yx = i, yy = j; } else if (c[i][j] == 'Z') { a[i][j] = 2, z[ct++] = {i, j}; } else { assert(0); } } } printf("%d\n", bfs()); } return 0; }
|