双向BFS。注意,任何一个点出队后,首先需要考虑ghost。
1 /* 3085 */ 2 #include <iostream> 3 #include <queue> 4 #include <cstdio> 5 #include <cstring> 6 #include <cstdlib> 7 #include <cmath> 8 using namespace std; 9 10 #define MAXN 805 11 12 typedef struct node_t { 13 int x, y; 14 node_t() {} 15 node_t(int xx, int yy) { 16 x = xx; y = yy; 17 } 18 } node_t; 19 20 int n, m; 21 node_t z[2], beg0, beg1; 22 char map[MAXN][MAXN]; 23 bool visit0[MAXN][MAXN]; 24 bool visit1[MAXN][MAXN]; 25 int dir[4][2] = { 26 -1,0,1,0,0,-1,0,1 27 }; 28 29 inline bool check(int x, int y) { 30 return x<0 || x>=n || y<0 || y>=m; 31 } 32 33 inline bool meetZ(int x, int y, int t) { 34 return abs(x-z[0].x)+abs(y-z[0].y)<=t+t || abs(x-z[1].x)+abs(y-z[1].y)<=t+t; 35 } 36 37 int bfs() { 38 int size; 39 int x, y, t = 0; 40 int i, j, k, r; 41 node_t nd; 42 queue<node_t> Q0; 43 queue<node_t> Q1; 44 45 memset(visit0, false, sizeof(visit0)); 46 memset(visit1, false, sizeof(visit1)); 47 visit0[beg0.x][beg0.y] = true; 48 visit1[beg1.x][beg1.y] = true; 49 Q0.push(beg0); 50 Q1.push(beg1); 51 52 while (!Q0.empty() || !Q1.empty()) { 53 ++t; 54 // Q0 55 r = 3; 56 while (r--) { 57 size = Q0.size(); 58 while (size--) { 59 nd = Q0.front(); 60 Q0.pop(); 61 if (meetZ(nd.x, nd.y, t)) 62 continue; 63 for (i=0; i<4; ++i) { 64 x = nd.x + dir[i][0]; 65 y = nd.y + dir[i][1]; 66 if (check(x, y) || visit0[x][y]) 67 continue; 68 if (map[x][y]==‘X‘ || meetZ(x, y, t)) 69 continue; 70 if (visit1[x][y]) 71 return t; 72 visit0[x][y] = true; 73 Q0.push(node_t(x, y)); 74 } 75 } 76 } 77 // Q1 78 size = Q1.size(); 79 while (size--) { 80 nd = Q1.front(); 81 Q1.pop(); 82 if (meetZ(nd.x, nd.y, t)) 83 continue; 84 for (i=0; i<4; ++i) { 85 x = nd.x + dir[i][0]; 86 y = nd.y + dir[i][1]; 87 if (check(x, y) || visit1[x][y]) 88 continue; 89 if (map[x][y]==‘X‘ || meetZ(x, y, t)) 90 continue; 91 if (visit0[x][y]) 92 return t; 93 visit1[x][y] = true; 94 Q1.push(node_t(x, y)); 95 } 96 } 97 } 98 99 return -1; 100 } 101 102 int main() { 103 int t; 104 int i, j, k; 105 106 #ifndef ONLINE_JUDGE 107 freopen("data.in", "r", stdin); 108 freopen("data.out", "w", stdout); 109 #endif 110 111 scanf("%d", &t); 112 while (t--) { 113 scanf("%d %d", &n, &m); 114 k = 0; 115 for (i=0; i<n; ++i) { 116 scanf("%s", map[i]); 117 for (j=0; j<m; ++j) { 118 if (map[i][j] == ‘Z‘) { 119 z[k].x = i; 120 z[k].y = j; 121 ++k; 122 } else if (map[i][j] == ‘M‘) { 123 beg0.x = i; 124 beg0.y = j; 125 } else if (map[i][j] == ‘G‘) { 126 beg1.x = i; 127 beg1.y = j; 128 } 129 } 130 } 131 k = bfs(); 132 printf("%d\n", k); 133 } 134 135 return 0; 136 }
时间: 2024-11-03 22:26:05