【題解】CSES 1192 Counting Rooms

【題目敘述】https://cses.fi/problemset/task/1192/

#include <iostream>
#include <queue>
using namespace std;
 
int n, m, a[1005][1005], ans, d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
string s;
 
int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i++){
        cin >> s;
        for (int j = 0; j < m; j++){
            if (s[j] == '.') a[i][j] = 1;
            else a[i][j] = 0;
        }
    }
    queue <pair<int, int> > q;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < m; j++){
            if (a[i][j] == 1){
                q.push({i, j});
                ans++;
                while (!q.empty()){
                    auto now = q.front();
                    q.pop();
                    for (int k = 0; k < 4; k++){
                        int x = now.first + d[k][0];
                        int y = now.second + d[k][1];
                        if (0 <= x && x < n && 0 <= y && y < m && a[x][y]){
                            a[x][y] = 0;
                            q.push({x, y});
                        }
                    }
                }
            }
        }
    }
    cout << ans << "\n";
}

分享本文 Share with friends