【HDOJ】3309 Roll The Cube
BFS,考虑一球进洞仅一球滚动以及两球重叠的情况即可。
1 /* 3309 */ 2 #include <iostream> 3 #include <queue> 4 #include <cstdio> 5 #include <cstring> 6 #include <cstdlib> 7 using namespace std; 8 9 #define MAXN 25 10 11 typedef struct { 12 int x[2], y[2]; 13 bool in[2]; 14 int t; 15 } node_t; 16 17 int n, m; 18 node_t beg; 19 bool visit[MAXN][MAXN][MAXN][MAXN]; 20 char map[MAXN][MAXN]; 21 int dir[4][2] = { 22 -1,0,1,0,0,-1,0,1 23 }; 24 25 inline bool check(int x, int y) { 26 return x<0 || x>=n || y<0 || y>=m; 27 } 28 29 int bfs() { 30 int i, j, k; 31 node_t d, nd; 32 queue<node_t> Q; 33 34 memset(visit, false, sizeof(visit)); 35 visit[beg.x[0]][beg.y[0]][beg.x[1]][beg.y[1]] = true; 36 Q.push(beg); 37 38 while (!Q.empty()) { 39 nd = Q.front(); 40 Q.pop(); 41 if (!nd.in[0]) { 42 if (nd.in[1] == false) { 43 if (map[nd.x[1]][nd.y[1]] == 'H') 44 nd.in[1] = true; 45 } 46 if (nd.in[1]) { 47 if (map[nd.x[0]][nd.y[0]]=='H' && (nd.x[0]!=nd.x[1] || nd.y[0]!=nd.y[1])) 48 nd.in[0] = true; 49 } else { 50 if (map[nd.x[0]][nd.y[0]]=='H') { 51 nd.in[0] = true; 52 } 53 } 54 } else { 55 if (!nd.in[1]) { 56 if (map[nd.x[1]][nd.y[1]]=='H' && (nd.x[0]!=nd.x[1] || nd.y[0]!=nd.y[1])) 57 nd.in[1] = true; 58 } 59 } 60 if (nd.in[0] && nd.in[1]) 61 return nd.t; 62 ++nd.t; 63 for (i=0; i<4; ++i) { 64 d = nd; 65 if (nd.in[0] == false) { 66 d.x[0] += dir[i][0]; 67 d.y[0] += dir[i][1]; 68 if (check(d.x[0], d.y[0])) 69 continue; 70 if (map[d.x[0]][d.y[0]] == '*') { 71 d.x[0] = nd.x[0]; 72 d.y[0] = nd.y[0]; 73 } 74 } 75 if (nd.in[1] == false) { 76 d.x[1] += dir[i][0]; 77 d.y[1] += dir[i][1]; 78 if (check(d.x[1], d.y[1])) 79 continue; 80 if (map[d.x[1]][d.y[1]] == '*') { 81 d.x[1] = nd.x[1]; 82 d.y[1] = nd.y[1]; 83 } 84 } 85 if (d.in[0]==false && d.in[1]==false) { 86 if (d.x[0]==d.x[1] && d.y[0]==d.y[1]) 87 continue; 88 } 89 if (visit[d.x[0]][d.y[0]][d.x[1]][d.y[1]]) 90 continue; 91 visit[d.x[0]][d.y[0]][d.x[1]][d.y[1]] = true; 92 Q.push(d); 93 } 94 } 95 96 return -1; 97 } 98 99 int main() { 100 int t; 101 int i, j, k; 102 103 #ifndef ONLINE_JUDGE 104 freopen("data.in", "r", stdin); 105 freopen("data.out", "w", stdout); 106 #endif 107 108 scanf("%d", &t); 109 beg.in[0] = beg.in[1] = false; 110 beg.t = 0; 111 while (t--) { 112 scanf("%d %d", &n, &m); 113 k = 0; 114 for (i=0; i<n; ++i) { 115 scanf("%s", map[i]); 116 for (j=0; j<m; ++j) { 117 if (map[i][j] == 'B') { 118 beg.x[k] = i; 119 beg.y[k] = j; 120 ++k; 121 } 122 } 123 } 124 k = bfs(); 125 if (k < 0) 126 puts("Sorry , sir , my poor program fails to get an answer."); 127 else 128 printf("%d\n", k); 129 } 130 131 return 0; 132 }