1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <bits/stdc++.h> #define ios ios::sync_with_stdio(0),cin.tie(0) using namespace std; int t; bool maze[1005][1005],visit[1005][1005]; int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1}; queue<int> qx,qy;
void bfs(int x,int y){ int now_x=x,now_y=y; qx.push(x); qy.push(y); while(!qx.empty()){ now_x = qx.front();now_y = qy.front(); visit[now_x][now_y]=1; for(int i=0;i<4;i++){ int nx = now_x+dx[i], ny = now_y+dy[i]; if(!visit[nx][ny] && maze[nx][ny]==1){ qx.push(nx); qy.push(ny); visit[nx][ny] = 1; } } qx.pop(); qy.pop(); } } int main(){ ios; cin>>t; while(t--){ int a,b;cin>>a>>b; memset(maze,0,sizeof(maze)); memset(visit,0,sizeof(visit)); for(int i=1;i<=a;i++){ for(int j=1;j<=b;j++){ char temp;cin>>temp; if(temp=='#')maze[i][j]=0; else maze[i][j]=1; } } int ans = 0; for(int i=1;i<=a;i++){ for(int j=1;j<=b;j++){ if(maze[i][j]==1 && visit[i][j]==0){ bfs(i,j); ans++; } } } cout<<ans<<endl; } }
|