#include #include #include #include using namespace std; int main() { int H, W, ans = 0; cin >> H >> W; vector> A(H, vector(W)); for (vector& i : A) { for (int& j : i) cin >> j; } vector> a(H, vector(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (!a[i][j] && A[i][j]) { ++ans; a[i][j] = true; queue> b; b.emplace(i, j); while (!b.empty()) { if (H - 1 != b.front().first) { if (!a[1 + b.front().first][b.front().second] && A[1 + b.front().first][b.front().second]) { a[1 + b.front().first][b.front().second] = true; b.emplace(1 + b.front().first, b.front().second); } } if (W - 1 != b.front().second) { if (!a[b.front().first][1 + b.front().second] && A[b.front().first][1 + b.front().second]) { a[b.front().first][1 + b.front().second] = true; b.emplace(b.front().first, 1 + b.front().second); } } if (b.front().first) { if (!a[b.front().first - 1][b.front().second] && A[b.front().first - 1][b.front().second]) { a[b.front().first - 1][b.front().second] = true; b.emplace(b.front().first - 1, b.front().second); } } if (b.front().second) { if (!a[b.front().first][b.front().second - 1] && A[b.front().first][b.front().second - 1]) { a[b.front().first][b.front().second - 1] = true; b.emplace(b.front().first, b.front().second - 1); } } b.pop(); } } } } cout << ans; }