【HDOJ】3085 Nightmare Ⅱ

时间:2021-04-13 20:41:15

双向BFS。注意,任何一个点出队后,首先需要考虑ghost。

 /* 3085 */
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std; #define MAXN 805 typedef struct node_t {
int x, y;
node_t() {}
node_t(int xx, int yy) {
x = xx; y = yy;
}
} node_t; int n, m;
node_t z[], beg0, beg1;
char map[MAXN][MAXN];
bool visit0[MAXN][MAXN];
bool visit1[MAXN][MAXN];
int dir[][] = {
-,,,,,-,,
}; inline bool check(int x, int y) {
return x< || x>=n || y< || y>=m;
} inline bool meetZ(int x, int y, int t) {
return abs(x-z[].x)+abs(y-z[].y)<=t+t || abs(x-z[].x)+abs(y-z[].y)<=t+t;
} int bfs() {
int size;
int x, y, t = ;
int i, j, k, r;
node_t nd;
queue<node_t> Q0;
queue<node_t> Q1; memset(visit0, false, sizeof(visit0));
memset(visit1, false, sizeof(visit1));
visit0[beg0.x][beg0.y] = true;
visit1[beg1.x][beg1.y] = true;
Q0.push(beg0);
Q1.push(beg1); while (!Q0.empty() || !Q1.empty()) {
++t;
// Q0
r = ;
while (r--) {
size = Q0.size();
while (size--) {
nd = Q0.front();
Q0.pop();
if (meetZ(nd.x, nd.y, t))
continue;
for (i=; i<; ++i) {
x = nd.x + dir[i][];
y = nd.y + dir[i][];
if (check(x, y) || visit0[x][y])
continue;
if (map[x][y]=='X' || meetZ(x, y, t))
continue;
if (visit1[x][y])
return t;
visit0[x][y] = true;
Q0.push(node_t(x, y));
}
}
}
// Q1
size = Q1.size();
while (size--) {
nd = Q1.front();
Q1.pop();
if (meetZ(nd.x, nd.y, t))
continue;
for (i=; i<; ++i) {
x = nd.x + dir[i][];
y = nd.y + dir[i][];
if (check(x, y) || visit1[x][y])
continue;
if (map[x][y]=='X' || meetZ(x, y, t))
continue;
if (visit0[x][y])
return t;
visit1[x][y] = true;
Q1.push(node_t(x, y));
}
}
} return -;
} int main() {
int t;
int i, j, k; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif scanf("%d", &t);
while (t--) {
scanf("%d %d", &n, &m);
k = ;
for (i=; i<n; ++i) {
scanf("%s", map[i]);
for (j=; j<m; ++j) {
if (map[i][j] == 'Z') {
z[k].x = i;
z[k].y = j;
++k;
} else if (map[i][j] == 'M') {
beg0.x = i;
beg0.y = j;
} else if (map[i][j] == 'G') {
beg1.x = i;
beg1.y = j;
}
}
}
k = bfs();
printf("%d\n", k);
} return ;
}