#include #include #include using namespace std; struct Union_Find { std::vector parent; std::vector rank; int N; Union_Find(int n) { N = n; parent = std::vector(N, -1); rank = std::vector(N, 0); } int find(int x) { if (parent[x] < 0) return x; return parent[x] = find(parent[x]); } int size(int x) { return -parent[find(x)]; } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (parent[x] > parent[y]) std::swap(x, y); parent[x] += parent[y]; parent[y] = x; return; } bool same(int x, int y) { return find(x) == find(y); } int group_count() { int K = 0; for (int i = 0; i < N; i++) { if (parent[i] < 0) K++; } return K; } std::vector members(int x) { std::vector v(0); int r = find(x); for (int i = 0; i < N; i++) { if (find(i) == r) v.push_back(i); } return v; } }; int main() { int H, W; int K = 0; int a, b, c; cin >> H >> W; vector> S(H, vector(W)); vector> T(H, vector(W, -1)); for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { cin >> S.at(y).at(x); if (S.at(y).at(x) == 1) { T.at(y).at(x) = K; K++; } } } Union_Find U(K); for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { if (S.at(y).at(x) == 1) { a = T.at(y).at(x); if (y < H - 1 && S.at(y + 1).at(x) == 1) { b = T.at(y + 1).at(x); U.unite(a, b); } if (x < W - 1 && S.at(y).at(x + 1) == 1) { c = T.at(y).at(x + 1); U.unite(a, c); } } } } cout << U.group_count() << endl; return 1; }