1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include <iostream> #include <queue>
using namespace std;
const int N = 1010;
int g[N][N]; int n, m; int x[] = {1, 0, -1, 0, 1, -1, 1, -1}; int y[] = {0, 1, 0, -1, 1, -1, -1, 1};
int main() { cin >> n >> m; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { char t; cin >> t; if (t == '.') g[i][j] = 0; else g[i][j] = 1; } } queue<pair<int, int>> visited; int cnt = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (g[i][j]) { visited.push({i, j}); g[i][j] = 0; cnt ++; } while(!visited.empty()) { int ox = visited.front().first, oy = visited.front().second; visited.pop(); for (int s = 0; s < 8; ++s) { int nx = ox + x[s]; int ny = oy + y[s]; if (g[nx][ny]) visited.push({nx, ny}); g[nx][ny] = 0; } } } } cout << cnt; }
|