Fork Copy #include<iostream> using namespace std; int n, m; int nt[700][700]; int checked[700][700]; int kq; int queuex[50000]; int queuey[50000]; int head, tail; void print(){ for (int i=0;i<n;i++){ for (int j=0;j<m;j++){ cout<<nt[i][j]<<" "; } cout<<endl; } cout<<endl; } void find(int x, int y, int s){ head=0; tail=0; queuex[tail]=x; queuey[tail]=y; while (head<=tail){ int topx=queuex[head]; int topy=queuey[head]; // cout<<head<<" "<<topx<<" "<<topy<<endl; head++; for (int dx=-1;dx<=1;dx++){ for (int dy=-1;dy<=1;dy++){ if (dx!=0||dy!=0){ int tmpx=topx+dx, tmpy=topy+dy; if (tmpx>=0 && tmpx<n && tmpy>=0 && tmpy<m && !checked[tmpx][tmpy] && nt[tmpx][tmpy]<=nt[topx][topy] && nt[tmpx][tmpy]<s){ tail++; queuex[tail]=tmpx; queuey[tail]=tmpy; checked[tmpx][tmpy]=1; } } } } } } void find2(int x, int y){ head=0; tail=0; queuex[tail]=x; queuey[tail]=y; checked[x][y]=1; while (head<=tail){ int topx=queuex[head]; int topy=queuey[head]; head++; for (int dx=-1;dx<=1;dx++){ for (int dy=-1;dy<=1;dy++){ int tmpx=topx+dx, tmpy=topy+dy; if (tmpx>=0 && tmpx<n && tmpy>=0 && tmpy<m && !checked[tmpx][tmpy]){ tail++; queuex[tail]=tmpx; queuey[tail]=tmpy; checked[tmpx][tmpy]=1; } } } } } int main(){ ios::sync_with_stdio(false); freopen("BaoVeNongTrai.txt","r",stdin); int T; cin>>T; for (int tc=1;tc<=T;++tc){ kq=0; cin>>n>>m; for (int i=0;i<n;i++){ for (int j=0;j<m;j++){ cin>>nt[i][j]; if (nt[i][j]==0) checked[i][j]=1; else checked[i][j]=0; } } for (int i=0;i<n;i++){ for (int j=0;j<m;j++){ if(!checked[i][j]) find(i, j, nt[i][j]); } } for (int i=0;i<n;i++){ for (int j=0;j<m;j++){ if (!checked[i][j]){ find2(i,j); kq++; } } } cout<<"#"<<tc<<" "<<kq<<endl; } }