#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef pair P; //typedef pair P; ll MOD = 1000000007; //ll INF = 1LL << 60; template void Fill(A (&array)[N], const T &val) { fill((T *)array, (T *)(array + N), val); } int a[3010][3010]; int main() { ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; int ans = 0; queue

one; for (ll i = 0; i < h; i++) { for (ll j = 0; j < w; j++) { cin >> a[i][j]; if (a[i][j] == 1) { one.push(P(j, i)); ans = 1; } } } if(one.empty()){ cout << 0 << endl; return 0; } queue

q; q.push(P(one.front().first , one.front().second)); one.pop(); int xl[] = {0, 1, 0, -1}; int yl[] = {-1, 0, 1, 0}; while (!one.empty()) { if (q.empty()) { while(true){ P pp = P(one.front().first, one.front().second); one.pop(); if(a[pp.second][pp.first]==1){ q.push(pp); ans++; break; }else{ if(one.empty()){ cout << ans << endl; return 0; } continue; } } } int x = q.front().first; int y = q.front().second; q.pop(); a[y][x] = 0; for (int i = 0; i < 4; i++) { int nx = x + xl[i]; int ny = y + yl[i]; if (nx < 0 || ny < 0 || nx >= w || ny >= h || a[ny][nx] == 0) continue; q.push(P(nx, ny)); a[ny][nx] = 0; } } cout << ans << endl; }