#include using namespace std; using int64 = long long; using uint64 = unsigned long long; int dr[4] = {1, 0, -1, 0}, dc[4] = {0, 1, 0, -1}; const int MAX_H = 3000; const int MAX_W = 3000; int H, W, A[MAX_H][MAX_W]; bool isVisited[MAX_H][MAX_W]; bool isInside(int r, int c) { return 0 <= r and r < H and 0 <= c and c < W; } void bfs(int r, int c) { queue> Q; isVisited[r][c] = true; Q.push(make_pair(r, c)); while (!Q.empty()) { auto pos = Q.front(); Q.pop(); for (int i = 0; i < 4; i++) { int nr = pos.first + dr[i], nc = pos.second + dc[i]; if (isInside(nr, nc) and !isVisited[nr][nc] and A[nr][nc] == 1) { isVisited[nr][nc] = true; Q.push(make_pair(nr, nc)); } } } } int counting() { int cnt = 0; for (int r = 0; r < H; r++) { for (int c = 0; c < W; c++) { if (!isVisited[r][c] and A[r][c] == 1) { cnt++; bfs(r, c); } } } return cnt; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cin >> H >> W; for (int r = 0; r < H; r++) { for (int c = 0; c < W; c++) { cin >> A[r][c]; } } cout << counting() << endl; return 0; }