fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4. #include <string>
  5. using namespace std;
  6.  
  7. int n, m;
  8. vector<vector<bool>> la;
  9. set<pair<int, int>> wall;
  10.  
  11. bool valid(int i, int j) {
  12. return i >= 0 && i < n && j >= 0 && j < m && !la[i][j] && wall.find({i, j}) == wall.end();
  13. }
  14.  
  15. void dfs(int i, int j) {
  16. if (!valid(i, j)) return;
  17. la[i][j] = true;
  18. dfs(i + 1, j);
  19. dfs(i - 1, j);
  20. dfs(i, j + 1);
  21. dfs(i, j - 1);
  22. }
  23.  
  24. int main() {
  25. cin >> n >> m;
  26.  
  27. la.resize(n, vector<bool>(m, false));
  28. vector<vector<int>> a(n, vector<int>(m, 0));
  29.  
  30. string ch;
  31. for (int i = 0; i < n; i++) {
  32. cin >> ch;
  33. for (int j = 0; j < m; j++) {
  34. if (ch[j] == '#') {
  35. a[i][j] = 1;
  36. wall.insert({i, j});
  37. } else {
  38. a[i][j] = 0;
  39. }
  40. }
  41. }
  42.  
  43. int nb = 0;
  44. for (int i = 0; i < n; i++) {
  45. for (int j = 0; j < m; j++) {
  46. if (!la[i][j] && wall.find({i, j}) == wall.end()) {
  47. dfs(i, j);
  48. nb++;
  49. }
  50. }
  51. }
  52.  
  53. cout << nb << endl;
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
0