#include using namespace std; const pair DXY[] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; struct dsu{ vector par, sz; dsu(int n) : par(n), sz(n, 1){ iota(par.begin(), par.end(), 0); } int root(int x){ if (par[x] == x) return x; return par[x] = root(par[x]); } bool merge(int x, int y){ x = root(x), y = root(y); if (x == y) return false; if (sz[x] < sz[y]) swap(x, y); par[y] = x, sz[x] += sz[y]; return true; } bool same(int x, int y){ return root(x) == root(y); } int size(int x){ return sz[root(x)]; } }; int main(){ int H, W; cin >> H >> W; vector> A(H, vector(W)); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ cin >> A[i][j]; } } auto id = [&](int i, int j){ return W*i+j; }; dsu uf(H*W); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ for (auto [dx, dy] : DXY){ int nx = i+dx, ny = j+dy; if (nx < 0 || H <= nx || ny < 0 || W <= ny) continue; if (A[i][j] && A[nx][ny]) uf.merge(id(i, j), id(nx, ny)); } } } set roots; for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ if (A[i][j]) roots.insert(uf.root(id(i, j))); } } cout << roots.size() << endl; }