首页 > 代码库 > 【HDOJ】1547 Bubble Shooter

【HDOJ】1547 Bubble Shooter

两次BFS,一次扫描关联点。一次扫描可能掉落的情况(即再次扫描所有非爆炸的联通点)。余下未被扫描的点均爆炸。

  1 #include <cstdio>  2 #include <cstring>  3 #include <queue>  4 #include <cstdlib>  5 #include <iostream>  6 using namespace std;  7   8 #define MAXN 105  9 char map[MAXN][MAXN]; 10 bool visit[MAXN][MAXN]; 11 int h, w, x, y; 12 int dir[8][2] = {-1,1, 1,1, -1,0, 0,1, 1,0, 0,-1, -1,-1, 1,-1}; 13  14 typedef struct node_t { 15     int x, y; 16     node_t() {} 17     node_t(int xx, int yy) { 18         x = xx; y = yy; 19     } 20 } node_t; 21  22 bool check(int x, int y) { 23     int ww = w; 24  25     if ((x&1) == 0) 26         ww = w-1; 27     if (x<1 || x>h || y<1 || y>ww || visit[x][y]) 28         return true; 29     return false; 30 } 31  32 void bfs_Oth(int x, int y) { 33     int i, j, nx, ny; 34     queue<node_t> Q; 35  36     visit[x][y] = true; 37     Q.push(node_t(x,y)); 38  39     while (!Q.empty()) { 40         node_t nd = Q.front(); 41         Q.pop(); 42         j = (nd.x & 1)<<1; 43         for (i=j; i<j+6; ++i) { 44             nx = nd.x + dir[i][0]; 45             ny = nd.y + dir[i][1]; 46             if (check(nx, ny) || map[nx][ny]==E) 47                 continue; 48             Q.push(node_t(nx, ny)); 49             visit[nx][ny] = true; 50         } 51     } 52 } 53  54 void bfs() { 55     int ans = 0; 56     int i, j, nx, ny; 57     char c = map[x][y]; 58     queue<node_t> Q; 59  60     memset(visit, false, sizeof(visit)); 61     visit[x][y] = true; 62     Q.push(node_t(x,y)); 63  64     while (!Q.empty()) { 65         node_t nd = Q.front(); 66         Q.pop(); 67         ++ans; 68         j = (nd.x & 1)<<1; 69         for (i=j; i<j+6; ++i) { 70             nx = nd.x + dir[i][0]; 71             ny = nd.y + dir[i][1]; 72             if (check(nx, ny) || map[nx][ny]!=c) 73                 continue; 74             Q.push(node_t(nx, ny)); 75             visit[nx][ny] = true; 76         } 77     } 78  79     if (ans < 3) { 80         printf("0\n"); 81         return ; 82     } 83  84     // search the other bubbles 85     for (j=1; map[1][j]; ++j) { 86         if (!visit[1][j] && map[1][j]!=E) { 87             bfs_Oth(1, j); 88         } 89     } 90  91     for (i=1; i<=h; ++i) { 92         for (j=1; map[i][j]; ++j) { 93             if (!visit[i][j] && map[i][j]!=E) 94                 ++ans; 95         } 96     } 97     printf("%d\n", ans); 98 } 99 100 101 int main() {102     int i, j;103 #ifndef ONLINE_JUDGE104     FILE *fin = freopen("data.in", "r", stdin);105 #endif106     while (scanf("%d%d%d%d", &h,&w,&x,&y)!=EOF) {107         for (i=1; i<=h; ++i) {108             scanf("%s", map[i]+1);109         }110         bfs();111 #ifndef ONLINE_JUDGE112         fflush(stdout);113 #endif114     }115 116     return 0;117 }

 

【HDOJ】1547 Bubble Shooter