fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int A,B;
  5. int arr[1000][1000]={};
  6. string str[1000];
  7. int X[4]={1,-1,0,0};
  8. int Y[4]={0,0,1,-1};
  9. int cnt=1;
  10.  
  11. void dfs(int x, int y){
  12. arr[x][y]=cnt;
  13. for(int i=0;i<4;i++){
  14. if(x+X[i]<A && x+X[i]>=0 && y+Y[i]>=0 && y+Y[i]<B && arr[x+X[i]][y+Y[i]]==0 && str[x+X[i]][y+Y[i]]=='.'){
  15. dfs(x+X[i],y+Y[i]);
  16. }
  17. //cout << str[x+X[i]]<< ' ' << y+Y[i] << ' ';
  18. }//cout << '\n';
  19. return ;
  20. }
  21.  
  22. int main() {
  23. cin >>A>>B;
  24. for(int i=0;i<A;i++){
  25. cin >> str[i];
  26. }for(int i=0;i<A;i++){
  27. for(int j=0;j<B;j++){
  28. if(str[i][j]=='.' && arr[i][j]==0){
  29. dfs(i,j);
  30. cnt++;
  31. //cout << i << ' ' << j << '\n';
  32. }
  33. }
  34. }cout << cnt-1 << '\n';
  35. }
Success #stdin #stdout 0s 5320KB
stdin
5 8
########
#..#...#
####.#.#
#..#...#
########
stdout
3