#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef pair P; #define MOD 1000000007 // 10^9 + 7 #define INF 1000000000 // 10^9 #define LLINF 1LL<<60 int H, W; bool field[3009][3009]; // 移動4方向のベクトル int dx[4] = { 1,0,-1,0 }; int dy[4] = { 0,1,0,-1 }; // x,yが範囲に入っているかどうか // 1 <= x <= N かつ 1 <= y <= Mが満たされてるかどうか bool isrange(int x, int y) { bool flag = true; if (x < 1 || H < x) flag = false; if (y < 1 || W < y) flag = false; return flag; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> H >> W; for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) cin >> field[i][j]; } queue

Q; int ans = 0; for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) { if (field[i][j]) { ans++; field[i][j] = false; Q.push(P(i, j)); while (!Q.empty()) { int cx = Q.front().first; int cy = Q.front().second; Q.pop(); for (int k = 0; k < 4; k++) { int nx = cx + dx[k]; int ny = cy + dy[k]; if (field[nx][ny]) { field[nx][ny] = false; Q.push(P(nx, ny)); } } } } } } cout << ans << endl; return 0; }