AHU-61 Lake Counting (并查集)
简单并查集
Code
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int MAXN = 10000 + 10; 4 const int dx[] = {1, -1, 0, 0, 1, -1, 1, -1}; 5 const int dy[] = {0, 0, 1, -1, 1, -1, -1, 1}; 6 int node[MAXN], pre[MAXN]; 7 8 int find(int x) { 9 return pre[x] == x ? x : pre[x] = find(pre[x]); 10 } 11 12 void join(int x, int y) { 13 int xx = find(x); 14 int yy = find(y); 15 if (xx != yy) { 16 pre[yy] = xx; 17 } 18 } 19 20 int main() { 21 int n, m, z; 22 while(~scanf("%d%d", &n, &m)) { 23 getchar(); 24 char ch; 25 for (int i = 0; i < n; ++i) { 26 for (int j = 0; j <= m; ++j) { //j多循环一次读换行 27 scanf("%c", &ch); 28 z = i * m + j; 29 if (ch == '.') node[z] = 0; 30 else if (ch == 'W') node[z] = 1; 31 pre[z] = z; 32 } 33 } 34 for (int i = 0; i < n*m; ++i) { 35 if (node[i] == 0) continue; 36 int x = i / m, y = i % m; 37 for (int j = 0; j < 8; ++j) { 38 int nx = x + dx[j], ny = y + dy[j]; 39 if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; 40 int nz = nx * m + ny; 41 if (node[nz] == 1) 42 join(i, nz); 43 } 44 } 45 set<int> root; 46 for (int i = 0; i < n*m; ++i) { 47 if (node[i] == 0) continue; 48 int nroot = find(i); 49 root.insert(nroot); 50 } 51 printf("%d\n", root.size()); 52 } 53 54 return 0; 55 }