#define _USE_MATH_DEFINES #include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define MT make_tuple #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)< >(b,vector(c,d)) #define vvv(a,b,c,d,e) vector > >(b,vv(a,c,d,e)) using ll = long long; using pii = pair; using vi = vector; using vll = vector; const int D[] = { 0,-1,0,1,0 }; class UnionFind{ int cnt; vector par, rank, size; public: UnionFind(){} UnionFind(int _n):cnt(_n), par(_n), rank(_n), size(_n, 1){ for(int i=0;i<_n;++i) par[i]=i; } int find(int k){ return (k==par[k])?k:(par[k]=find(par[k])); } int operator[](int k){ return find(k); } int getSize(int k){ return size[find(k)]; } void unite(int x, int y){ x = find(x); y = find(y); if(x==y) return; --cnt; if(rank[x] < rank[y]){ par[x] = y; size[y] += size[x]; }else{ par[y] = x; size[x] += size[y]; if(rank[y] == rank[x]) ++rank[x]; } } int count(){ return cnt; } }; bitset<3001> A[3001]; int main() { int H, W; cin >> H >> W; UnionFind uf(H*W + 1); auto f = [&](int y, int x) { RT y*W + x; }; rep(y, H)rep(x, W) { int z; scanf("%d", &z); A[y][x] = z; if (!z)uf.unite(H*W, f(y, x)); } rep(y, H)rep(x, W)if (A[y][x]) { if (A[y + 1][x])uf.unite(f(y, x), f(y + 1, x)); if (A[y][x + 1])uf.unite(f(y, x), f(y, x + 1)); } cout << uf.count() - 1 << endl; }