#include #include using namespace std; struct UnionFind { int n; vector par; vector size_; int whole; UnionFind(int n_) : n(n_), par((size_t)n_), size_((size_t)n_,1), whole(n_){ for(int i = 0; n > i; i++)par[i] = i; } int root(int x){ if(par[x] == x)return x; return par[x] = root(par[x]); } void unite(int a,int b){ int ra = root(a); int rb = root(b); if(ra==rb)return; if(size(ra) > size(rb)) swap(ra,rb); par[ra] = rb; size_[rb] += size_[ra]; whole--; } bool same(int a, int b){ return root(a) == root(b); } int size(int a){ return size_[root(a)]; } void debug(){ for(int i = 0; n > i; i++){ cout << size_[root(i)] << " "; } cout << endl; return; } }; int main(){ int h,w; scanf("%d%d",&h,&w); vector> A(h,vector(w)); for(int i = 0; h > i; i++){ for(int j = 0; w > j; j++){ scanf("%d",&A[i][j]); } } UnionFind B(h*w); int zero = 0; for(int i = 0; h > i; i++){ for(int j = 0; w > j; j++){ if(A[i][j] == 1){ if(i+1 != h && A[i+1][j] == 1){ B.unite(w*i+j,w*(i+1)+j); } if(j+1 != w && A[i][j+1] == 1){ B.unite(w*i+j,w*i+j+1); } }else zero++; } } cout << B.whole - zero << endl; }