Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <fstream>
- #include <queue>
- using namespace std;
- typedef long long ll;
- const int INF = 2e9;
- const int di[4] = {-1, 1, 0, 0};
- const int dj[4] = {0, 0, -1, 1};
- int count_rooms(vector<vector<char>> & mat, int n, int m) {
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- int res = 0;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(mat[i][j] == '.' and !visited[i][j]) {
- res++;
- queue<int> q;
- q.push(i);
- q.push(j);
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- for(int k = 0; k < 4; k++) {
- int ti = ci + di[k];
- int tj = cj + dj[k];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj]) {
- q.push(ti);
- q.push(tj);
- visited[ti][tj] = true;
- }
- }
- }
- }
- }
- }
- return res;
- }
- int main() {
- ios_base::sync_with_stdio(false);
- ifstream cin("in.txt");
- int n, m;
- cin >> n >> m;
- vector<vector<char>> mat(n, vector<char>(m));
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- }
- }
- int res = INF;
- for(int row = 0; row < n; row++) {
- vector<vector<char>> tmp(n - 1);
- int ci = 0;
- for(int i = 0; i < n; i++) {
- if(row != i) {
- for(int j = 0; j < m; j++) {
- tmp[ci].push_back(mat[i][j]);
- }
- ci++;
- }
- }
- res = min(res, count_rooms(tmp, n - 1, m));
- }
- for(int col = 0; col < m; col++) {
- vector<vector<char>> tmp(n);
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(j != col) {
- tmp[i].push_back(mat[i][j]);
- }
- }
- }
- res = min(res, count_rooms(tmp, n, m - 1));
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment