Advertisement
tepyotin2

Counting Rooms

May 1st, 2025
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n, m;
  6. char grid[1001][1001];
  7. bool visited[1001][1001];
  8. int dx[] = {-1, 1, 0, 0};
  9. int dy[] = {0, 0, 1, -1};
  10. int ans;
  11.  
  12. void dfs(int x, int y){
  13.     if(visited[x][y] || x<0 || x>n-1 || y<0 || y>m-1){
  14.         return;
  15.     }
  16.     //cout << "x: " << x << ", y: " << y << '\n';
  17.     visited[x][y] = true;
  18.     for(int i=0; i<4; i++){
  19.         int nx = x+dx[i];
  20.         int ny = y+dy[i];
  21.         //cout << "nx: " << nx << ", ny: " << ny << '\n';
  22.         if(!visited[nx][ny] && nx>=0 && nx<=n-1 && ny>=0 && ny<=m-1 && grid[nx][ny] == '.'){
  23.             dfs(nx, ny);
  24.         }
  25.     }
  26. }
  27.  
  28. int main(){
  29.     //freopen("rooms.in", "r", stdin);
  30.    
  31.     cin >> n >> m;
  32.     string s;
  33.     for(int i=0; i<n; i++){
  34.         cin >> s;
  35.         for(int j=0; j<m; j++){
  36.             grid[i][j] = s[j];
  37.             //if(grid[i][j] == '.') cout << " ";
  38.             //cout << grid[i][j];
  39.         }
  40.         //cout << '\n';
  41.     }
  42.     for(int i=0; i<n; i++){
  43.         for(int j=0; j<m; j++){
  44.             if(!visited[i][j] && grid[i][j] == '.'){
  45.                 //cout << "i: " << i << ", j: " << j << ", grid[i][j]: " << grid[i][j] << '\n';
  46.                 ans++;
  47.                 dfs(i, j);
  48.             }
  49.         }
  50.     }
  51.     cout << ans << '\n';
  52.    
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement